context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.PerfTests.Bench.SBE.FIX { public class MassQuote { public const ushort TemplateId = (ushort)105; public const byte TemplateVersion = (byte)0; public const ushort BlockLength = (ushort)62; public const string SematicType = "i"; private readonly MassQuote _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public MassQuote() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = TemplateVersion; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(_limit); _limit = value; } } public const int QuoteReqIDSchemaId = 131; public static string QuoteReqIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteReqIDNullValue = (byte)0; public const byte QuoteReqIDMinValue = (byte)32; public const byte QuoteReqIDMaxValue = (byte)126; public const int QuoteReqIDLength = 23; public byte GetQuoteReqID(int index) { if (index < 0 || index >= 23) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 0 + (index * 1)); } public void SetQuoteReqID(int index, byte value) { if (index < 0 || index >= 23) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 0 + (index * 1), value); } public const string QuoteReqIDCharacterEncoding = "UTF-8"; public int GetQuoteReqID(byte[] dst, int dstOffset) { const int length = 23; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 0, dst, dstOffset, length); return length; } public void SetQuoteReqID(byte[] src, int srcOffset) { const int length = 23; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 0, src, srcOffset, length); } public const int QuoteIDSchemaId = 117; public static string QuoteIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteIDNullValue = (byte)0; public const byte QuoteIDMinValue = (byte)32; public const byte QuoteIDMaxValue = (byte)126; public const int QuoteIDLength = 10; public byte GetQuoteID(int index) { if (index < 0 || index >= 10) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 23 + (index * 1)); } public void SetQuoteID(int index, byte value) { if (index < 0 || index >= 10) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 23 + (index * 1), value); } public const string QuoteIDCharacterEncoding = "UTF-8"; public int GetQuoteID(byte[] dst, int dstOffset) { const int length = 10; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 23, dst, dstOffset, length); return length; } public void SetQuoteID(byte[] src, int srcOffset) { const int length = 10; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 23, src, srcOffset, length); } public const int MMAccountSchemaId = 9771; public static string MMAccountMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte MMAccountNullValue = (byte)0; public const byte MMAccountMinValue = (byte)32; public const byte MMAccountMaxValue = (byte)126; public const int MMAccountLength = 12; public byte GetMMAccount(int index) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 33 + (index * 1)); } public void SetMMAccount(int index, byte value) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 33 + (index * 1), value); } public const string MMAccountCharacterEncoding = "UTF-8"; public int GetMMAccount(byte[] dst, int dstOffset) { const int length = 12; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 33, dst, dstOffset, length); return length; } public void SetMMAccount(byte[] src, int srcOffset) { const int length = 12; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 33, src, srcOffset, length); } public const int ManualOrderIndicatorSchemaId = 1028; public static string ManualOrderIndicatorMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public BooleanType ManualOrderIndicator { get { return (BooleanType)_buffer.Uint8Get(_offset + 45); } set { _buffer.Uint8Put(_offset + 45, (byte)value); } } public const int CustOrderHandlingInstSchemaId = 1031; public static string CustOrderHandlingInstMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "char"; } return ""; } public CustOrderHandlingInst CustOrderHandlingInst { get { return (CustOrderHandlingInst)_buffer.CharGet(_offset + 46); } set { _buffer.CharPut(_offset + 46, (byte)value); } } public const int CustomerOrFirmSchemaId = 204; public static string CustomerOrFirmMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public CustomerOrFirm CustomerOrFirm { get { return (CustomerOrFirm)_buffer.Uint8Get(_offset + 47); } set { _buffer.Uint8Put(_offset + 47, (byte)value); } } public const int SelfMatchPreventionIDSchemaId = 7928; public static string SelfMatchPreventionIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SelfMatchPreventionIDNullValue = (byte)0; public const byte SelfMatchPreventionIDMinValue = (byte)32; public const byte SelfMatchPreventionIDMaxValue = (byte)126; public const int SelfMatchPreventionIDLength = 12; public byte GetSelfMatchPreventionID(int index) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 48 + (index * 1)); } public void SetSelfMatchPreventionID(int index, byte value) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 48 + (index * 1), value); } public const string SelfMatchPreventionIDCharacterEncoding = "UTF-8"; public int GetSelfMatchPreventionID(byte[] dst, int dstOffset) { const int length = 12; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 48, dst, dstOffset, length); return length; } public void SetSelfMatchPreventionID(byte[] src, int srcOffset) { const int length = 12; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 48, src, srcOffset, length); } public const int CtiCodeSchemaId = 9702; public static string CtiCodeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public CtiCode CtiCode { get { return (CtiCode)_buffer.CharGet(_offset + 60); } set { _buffer.CharPut(_offset + 60, (byte)value); } } public const int MMProtectionResetSchemaId = 9773; public static string MMProtectionResetMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public MMProtectionReset MMProtectionReset { get { return (MMProtectionReset)_buffer.CharGet(_offset + 61); } set { _buffer.CharPut(_offset + 61, (byte)value); } } private readonly QuoteSetsGroup _quoteSets = new QuoteSetsGroup(); public const long QuoteSetsSchemaId = 296; public QuoteSetsGroup QuoteSets { get { _quoteSets.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _quoteSets; } } public QuoteSetsGroup QuoteSetsCount(int count) { _quoteSets.WrapForEncode(_parentMessage, _buffer, count); return _quoteSets; } public class QuoteSetsGroup { private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding(); private MassQuote _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(MassQuote parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _count = _dimensions.NumInGroup; _blockLength = _dimensions.BlockLength; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + 3; } public void WrapForEncode(MassQuote parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.NumInGroup = (byte)count; _dimensions.BlockLength = (ushort)24; _index = -1; _count = count; _blockLength = 24; parentMessage.Limit = parentMessage.Limit + 3; } public int Count { get { return _count; } } public bool HasNext { get { return _index + 1 < _count; } } public QuoteSetsGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int QuoteSetIDSchemaId = 302; public static string QuoteSetIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteSetIDNullValue = (byte)0; public const byte QuoteSetIDMinValue = (byte)32; public const byte QuoteSetIDMaxValue = (byte)126; public const int QuoteSetIDLength = 3; public byte GetQuoteSetID(int index) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 0 + (index * 1)); } public void SetQuoteSetID(int index, byte value) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 0 + (index * 1), value); } public const string QuoteSetIDCharacterEncoding = "UTF-8"; public int GetQuoteSetID(byte[] dst, int dstOffset) { const int length = 3; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 0, dst, dstOffset, length); return length; } public void SetQuoteSetID(byte[] src, int srcOffset) { const int length = 3; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 0, src, srcOffset, length); } public const int UnderlyingSecurityDescSchemaId = 307; public static string UnderlyingSecurityDescMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte UnderlyingSecurityDescNullValue = (byte)0; public const byte UnderlyingSecurityDescMinValue = (byte)32; public const byte UnderlyingSecurityDescMaxValue = (byte)126; public const int UnderlyingSecurityDescLength = 20; public byte GetUnderlyingSecurityDesc(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 3 + (index * 1)); } public void SetUnderlyingSecurityDesc(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 3 + (index * 1), value); } public const string UnderlyingSecurityDescCharacterEncoding = "UTF-8"; public int GetUnderlyingSecurityDesc(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 3, dst, dstOffset, length); return length; } public void SetUnderlyingSecurityDesc(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 3, src, srcOffset, length); } public const int TotQuoteEntriesSchemaId = 304; public static string TotQuoteEntriesMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const byte TotQuoteEntriesNullValue = (byte)255; public const byte TotQuoteEntriesMinValue = (byte)0; public const byte TotQuoteEntriesMaxValue = (byte)254; public byte TotQuoteEntries { get { return _buffer.Uint8Get(_offset + 23); } set { _buffer.Uint8Put(_offset + 23, value); } } private readonly QuoteEntriesGroup _quoteEntries = new QuoteEntriesGroup(); public const long QuoteEntriesSchemaId = 295; public QuoteEntriesGroup QuoteEntries { get { _quoteEntries.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _quoteEntries; } } public QuoteEntriesGroup QuoteEntriesCount(int count) { _quoteEntries.WrapForEncode(_parentMessage, _buffer, count); return _quoteEntries; } public class QuoteEntriesGroup { private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding(); private MassQuote _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(MassQuote parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _count = _dimensions.NumInGroup; _blockLength = _dimensions.BlockLength; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + 3; } public void WrapForEncode(MassQuote parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.NumInGroup = (byte)count; _dimensions.BlockLength = (ushort)90; _index = -1; _count = count; _blockLength = 90; parentMessage.Limit = parentMessage.Limit + 3; } public int Count { get { return _count; } } public bool HasNext { get { return _index + 1 < _count; } } public QuoteEntriesGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int QuoteEntryIDSchemaId = 299; public static string QuoteEntryIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteEntryIDNullValue = (byte)0; public const byte QuoteEntryIDMinValue = (byte)32; public const byte QuoteEntryIDMaxValue = (byte)126; public const int QuoteEntryIDLength = 10; public byte GetQuoteEntryID(int index) { if (index < 0 || index >= 10) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 0 + (index * 1)); } public void SetQuoteEntryID(int index, byte value) { if (index < 0 || index >= 10) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 0 + (index * 1), value); } public const string QuoteEntryIDCharacterEncoding = "UTF-8"; public int GetQuoteEntryID(byte[] dst, int dstOffset) { const int length = 10; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 0, dst, dstOffset, length); return length; } public void SetQuoteEntryID(byte[] src, int srcOffset) { const int length = 10; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 0, src, srcOffset, length); } public const int SymbolSchemaId = 55; public static string SymbolMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SymbolNullValue = (byte)0; public const byte SymbolMinValue = (byte)32; public const byte SymbolMaxValue = (byte)126; public const int SymbolLength = 6; public byte GetSymbol(int index) { if (index < 0 || index >= 6) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 10 + (index * 1)); } public void SetSymbol(int index, byte value) { if (index < 0 || index >= 6) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 10 + (index * 1), value); } public const string SymbolCharacterEncoding = "UTF-8"; public int GetSymbol(byte[] dst, int dstOffset) { const int length = 6; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 10, dst, dstOffset, length); return length; } public void SetSymbol(byte[] src, int srcOffset) { const int length = 6; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 10, src, srcOffset, length); } public const int SecurityDescSchemaId = 107; public static string SecurityDescMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SecurityDescNullValue = (byte)0; public const byte SecurityDescMinValue = (byte)32; public const byte SecurityDescMaxValue = (byte)126; public const int SecurityDescLength = 20; public byte GetSecurityDesc(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 16 + (index * 1)); } public void SetSecurityDesc(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 16 + (index * 1), value); } public const string SecurityDescCharacterEncoding = "UTF-8"; public int GetSecurityDesc(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 16, dst, dstOffset, length); return length; } public void SetSecurityDesc(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 16, src, srcOffset, length); } public const int SecurityTypeSchemaId = 167; public static string SecurityTypeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SecurityTypeNullValue = (byte)0; public const byte SecurityTypeMinValue = (byte)32; public const byte SecurityTypeMaxValue = (byte)126; public const int SecurityTypeLength = 3; public byte GetSecurityType(int index) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 36 + (index * 1)); } public void SetSecurityType(int index, byte value) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 36 + (index * 1), value); } public const string SecurityTypeCharacterEncoding = "UTF-8"; public int GetSecurityType(byte[] dst, int dstOffset) { const int length = 3; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 36, dst, dstOffset, length); return length; } public void SetSecurityType(byte[] src, int srcOffset) { const int length = 3; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 36, src, srcOffset, length); } public const int SecurityIDSchemaId = 48; public static string SecurityIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const long SecurityIDNullValue = -9223372036854775808L; public const long SecurityIDMinValue = -9223372036854775807L; public const long SecurityIDMaxValue = 9223372036854775807L; public long SecurityID { get { return _buffer.Int64GetLittleEndian(_offset + 39); } set { _buffer.Int64PutLittleEndian(_offset + 39, value); } } public const int SecurityIDSourceSchemaId = 22; public static string SecurityIDSourceMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public SecurityIDSource SecurityIDSource { get { return (SecurityIDSource)_buffer.CharGet(_offset + 47); } set { _buffer.CharPut(_offset + 47, (byte)value); } } public const int TransactTimeSchemaId = 60; public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "UTCTimestamp"; } return ""; } public const ulong TransactTimeNullValue = 0x8000000000000000UL; public const ulong TransactTimeMinValue = 0x0UL; public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL; public ulong TransactTime { get { return _buffer.Uint64GetLittleEndian(_offset + 48); } set { _buffer.Uint64PutLittleEndian(_offset + 48, value); } } public const int BidPxSchemaId = 132; public static string BidPxMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "Price"; } return ""; } private readonly OptionalPrice _bidPx = new OptionalPrice(); public OptionalPrice BidPx { get { _bidPx.Wrap(_buffer, _offset + 56, _actingVersion); return _bidPx; } } public const int BidSizeSchemaId = 134; public static string BidSizeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const long BidSizeNullValue = -9223372036854775808L; public const long BidSizeMinValue = -9223372036854775807L; public const long BidSizeMaxValue = 9223372036854775807L; public long BidSize { get { return _buffer.Int64GetLittleEndian(_offset + 65); } set { _buffer.Int64PutLittleEndian(_offset + 65, value); } } public const int OfferPxSchemaId = 133; public static string OfferPxMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "Price"; } return ""; } private readonly OptionalPrice _offerPx = new OptionalPrice(); public OptionalPrice OfferPx { get { _offerPx.Wrap(_buffer, _offset + 73, _actingVersion); return _offerPx; } } public const int OfferSizeSchemaId = 135; public static string OfferSizeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const long OfferSizeNullValue = -9223372036854775808L; public const long OfferSizeMinValue = -9223372036854775807L; public const long OfferSizeMaxValue = 9223372036854775807L; public long OfferSize { get { return _buffer.Int64GetLittleEndian(_offset + 82); } set { _buffer.Int64PutLittleEndian(_offset + 82, 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.Runtime.InteropServices; using System.IO; using System.Drawing.Internal; using Gdip = System.Drawing.SafeNativeMethods.Gdip; using System.Runtime.Serialization; namespace System.Drawing.Imaging { /// <summary> /// Defines a graphic metafile. A metafile contains records that describe a sequence of graphics operations that /// can be recorded and played back. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public sealed partial class Metafile : Image { // GDI+ doesn't handle filenames over MAX_PATH very well private const int MaxPath = 260; /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and /// <see cref='WmfPlaceableFileHeader'/>. /// </summary> public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) : this(hmetafile, wmfHeader, false) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and /// <see cref='WmfPlaceableFileHeader'/>. /// </summary> public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader, bool deleteWmf) { Gdip.CheckStatus(Gdip.GdipCreateMetafileFromWmf(new HandleRef(null, hmetafile), deleteWmf, wmfHeader, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and /// <see cref='WmfPlaceableFileHeader'/>. /// </summary> public Metafile(IntPtr henhmetafile, bool deleteEmf) { Gdip.CheckStatus(Gdip.GdipCreateMetafileFromEmf(new HandleRef(null, henhmetafile), deleteEmf, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified filename. /// </summary> public Metafile(string filename) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(filename); Gdip.CheckStatus(Gdip.GdipCreateMetafileFromFile(filename, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified stream. /// </summary> public Metafile(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); Gdip.CheckStatus(Gdip.GdipCreateMetafileFromStream(new GPStream(stream), out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context. /// </summary> public Metafile(IntPtr referenceHdc, EmfType emfType) : this(referenceHdc, emfType, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context. /// </summary> public Metafile(IntPtr referenceHdc, EmfType emfType, string description) { Gdip.CheckStatus(Gdip.GdipRecordMetafile( new HandleRef(null, referenceHdc), emfType, NativeMethods.NullHandleRef, MetafileFrameUnit.GdiCompatible, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, RectangleF frameRect) : this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) : this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { Gdip.CheckStatus(Gdip.GdipRecordMetafile( new HandleRef(null, referenceHdc), type, ref frameRect, frameUnit, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect) : this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) : this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string desc) { IntPtr metafile = IntPtr.Zero; if (frameRect.IsEmpty) { Gdip.CheckStatus(Gdip.GdipRecordMetafile( new HandleRef(null, referenceHdc), type, NativeMethods.NullHandleRef, MetafileFrameUnit.GdiCompatible, desc, out metafile)); } else { Gdip.CheckStatus(Gdip.GdipRecordMetafileI( new HandleRef(null, referenceHdc), type, ref frameRect, frameUnit, desc, out metafile)); } SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc) : this(fileName, referenceHdc, EmfType.EmfPlusDual, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, EmfType type) : this(fileName, referenceHdc, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, EmfType type, string description) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); Gdip.CheckStatus(Gdip.GdipRecordMetafileFileName( fileName, new HandleRef(null, referenceHdc), type, NativeMethods.NullHandleRef, MetafileFrameUnit.GdiCompatible, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect) : this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(fileName, referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, string desc) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, desc) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); if (fileName.Length > MaxPath) throw new PathTooLongException(); Gdip.CheckStatus(Gdip.GdipRecordMetafileFileName( fileName, new HandleRef(null, referenceHdc), type, ref frameRect, frameUnit, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect) : this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(fileName, referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, string description) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, description) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); IntPtr metafile = IntPtr.Zero; if (frameRect.IsEmpty) { Gdip.CheckStatus(Gdip.GdipRecordMetafileFileName( fileName, new HandleRef(null, referenceHdc), type, NativeMethods.NullHandleRef, frameUnit, description, out metafile)); } else { Gdip.CheckStatus(Gdip.GdipRecordMetafileFileNameI( fileName, new HandleRef(null, referenceHdc), type, ref frameRect, frameUnit, description, out metafile)); } SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc) : this(stream, referenceHdc, EmfType.EmfPlusDual, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, EmfType type) : this(stream, referenceHdc, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, EmfType type, string description) { Gdip.CheckStatus(Gdip.GdipRecordMetafileStream( new GPStream(stream), new HandleRef(null, referenceHdc), type, NativeMethods.NullHandleRef, MetafileFrameUnit.GdiCompatible, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect) : this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) : this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(stream, referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { Gdip.CheckStatus(Gdip.GdipRecordMetafileStream( new GPStream(stream), new HandleRef(null, referenceHdc), type, ref frameRect, frameUnit, description, out IntPtr metafile)); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect) : this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) : this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(stream, referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { IntPtr metafile = IntPtr.Zero; if (frameRect.IsEmpty) { Gdip.CheckStatus(Gdip.GdipRecordMetafileStream( new GPStream(stream), new HandleRef(null, referenceHdc), type, NativeMethods.NullHandleRef, frameUnit, description, out metafile)); } else { Gdip.CheckStatus(Gdip.GdipRecordMetafileStreamI( new GPStream(stream), new HandleRef(null, referenceHdc), type, ref frameRect, frameUnit, description, out metafile)); } SetNativeImage(metafile); } private Metafile(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) { MetafileHeader header = new MetafileHeader { wmf = new MetafileHeaderWmf() }; Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromWmf(new HandleRef(null, hmetafile), wmfHeader, header.wmf)); return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(IntPtr henhmetafile) { MetafileHeader header = new MetafileHeader { emf = new MetafileHeaderEmf() }; Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromEmf(new HandleRef(null, henhmetafile), header.emf)); return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(string fileName) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); MetafileHeader header = new MetafileHeader(); IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromFile(fileName, memory)); int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(Stream stream) { MetafileHeader header; IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromStream(new GPStream(stream), memory)); int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; header = new MetafileHeader(); if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with this <see cref='Metafile'/>. /// </summary> public MetafileHeader GetMetafileHeader() { MetafileHeader header; IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { Gdip.CheckStatus(Gdip.GdipGetMetafileHeaderFromMetafile(new HandleRef(this, nativeImage), memory)); int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; header = new MetafileHeader(); if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns a Windows handle to an enhanced <see cref='Metafile'/>. /// </summary> public IntPtr GetHenhmetafile() { Gdip.CheckStatus(Gdip.GdipGetHemfFromMetafile(new HandleRef(this, nativeImage), out IntPtr hEmf)); return hEmf; } /// <summary> /// Plays an EMF+ file. /// </summary> public void PlayRecord(EmfPlusRecordType recordType, int flags, int dataSize, byte[] data) { // Used in conjunction with Graphics.EnumerateMetafile to play an EMF+ // The data must be DWORD aligned if it's an EMF or EMF+. It must be // WORD aligned if it's a WMF. Gdip.CheckStatus(Gdip.GdipPlayMetafileRecord( new HandleRef(this, nativeImage), recordType, flags, dataSize, data)); } /// <summary> /// Create a new metafile object from a native metafile handle. /// </summary> internal static Metafile FromGDIplus(IntPtr nativeImage) { Metafile metafile = new Metafile(); metafile.SetNativeImage(nativeImage); return metafile; } private Metafile() { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// JobScheduleOperations operations. /// </summary> internal partial class JobScheduleOperations : IServiceOperations<AutomationClient>, IJobScheduleOperations { /// <summary> /// Initializes a new instance of the JobScheduleOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal JobScheduleOperations(AutomationClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutomationClient /// </summary> public AutomationClient Client { get; private set; } /// <summary> /// Delete the job schedule identified by job schedule name. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, System.Guid jobScheduleId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // 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("automationAccountName", automationAccountName); tracingParameters.Add("jobScheduleId", jobScheduleId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobSchedules/{jobScheduleId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{jobScheduleId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobScheduleId, Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve the job schedule identified by job schedule name. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<JobSchedule>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, System.Guid jobScheduleId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // 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("automationAccountName", automationAccountName); tracingParameters.Add("jobScheduleId", jobScheduleId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobSchedules/{jobScheduleId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{jobScheduleId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobScheduleId, Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<JobSchedule>(); _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) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobSchedule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create a job schedule. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> /// <param name='parameters'> /// The parameters supplied to the create job schedule operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<JobSchedule>> CreateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, System.Guid jobScheduleId, JobScheduleCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // 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("automationAccountName", automationAccountName); tracingParameters.Add("jobScheduleId", jobScheduleId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobSchedules/{jobScheduleId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{jobScheduleId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobScheduleId, Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<JobSchedule>(); _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) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobSchedule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve a list of job schedules. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<JobSchedule>>> ListByAutomationAccountWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // 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("automationAccountName", automationAccountName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccount", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobSchedules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<JobSchedule>>(); _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) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobSchedule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve a list of job schedules. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </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> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<JobSchedule>>> ListByAutomationAccountNextWithHttpMessagesAsync(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, "ListByAutomationAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<JobSchedule>>(); _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) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobSchedule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.14.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Prediction API Version v1.3 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/prediction/docs/developer-guide'>Prediction API</a> * <tr><th>API Version<td>v1.3 * <tr><th>API Rev<td>20160511 (496) * <tr><th>API Docs * <td><a href='https://developers.google.com/prediction/docs/developer-guide'> * https://developers.google.com/prediction/docs/developer-guide</a> * <tr><th>Discovery Name<td>prediction * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Prediction API can be found at * <a href='https://developers.google.com/prediction/docs/developer-guide'>https://developers.google.com/prediction/docs/developer-guide</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Prediction.v1_3 { /// <summary>The Prediction Service.</summary> public class PredictionService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1.3"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public PredictionService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PredictionService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { hostedmodels = new HostedmodelsResource(this); training = new TrainingResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "prediction"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/prediction/v1.3/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "prediction/v1.3/"; } } /// <summary>Available OAuth 2.0 scopes for use with the Prediction API.</summary> public class Scope { /// <summary>Manage your data and permissions in Google Cloud Storage</summary> public static string DevstorageFullControl = "https://www.googleapis.com/auth/devstorage.full_control"; /// <summary>View your data in Google Cloud Storage</summary> public static string DevstorageReadOnly = "https://www.googleapis.com/auth/devstorage.read_only"; /// <summary>Manage your data in Google Cloud Storage</summary> public static string DevstorageReadWrite = "https://www.googleapis.com/auth/devstorage.read_write"; /// <summary>Manage your data in the Google Prediction API</summary> public static string Prediction = "https://www.googleapis.com/auth/prediction"; } private readonly HostedmodelsResource hostedmodels; /// <summary>Gets the Hostedmodels resource.</summary> public virtual HostedmodelsResource Hostedmodels { get { return hostedmodels; } } private readonly TrainingResource training; /// <summary>Gets the Training resource.</summary> public virtual TrainingResource Training { get { return training; } } } ///<summary>A base abstract class for Prediction requests.</summary> public abstract class PredictionBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new PredictionBaseServiceRequest instance.</summary> protected PredictionBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Prediction parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "hostedmodels" collection of methods.</summary> public class HostedmodelsResource { private const string Resource = "hostedmodels"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public HostedmodelsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Submit input and request an output against a hosted model</summary> /// <param name="body">The body of the request.</param> /// <param name="hostedModelName">The name of a hosted model</param> public virtual PredictRequest Predict(Google.Apis.Prediction.v1_3.Data.Input body, string hostedModelName) { return new PredictRequest(service, body, hostedModelName); } /// <summary>Submit input and request an output against a hosted model</summary> public class PredictRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_3.Data.Output> { /// <summary>Constructs a new Predict request.</summary> public PredictRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_3.Data.Input body, string hostedModelName) : base(service) { HostedModelName = hostedModelName; Body = body; InitParameters(); } /// <summary>The name of a hosted model</summary> [Google.Apis.Util.RequestParameterAttribute("hostedModelName", Google.Apis.Util.RequestParameterType.Path)] public virtual string HostedModelName { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_3.Data.Input Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "predict"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "hostedmodels/{hostedModelName}/predict"; } } /// <summary>Initializes Predict parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "hostedModelName", new Google.Apis.Discovery.Parameter { Name = "hostedModelName", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "training" collection of methods.</summary> public class TrainingResource { private const string Resource = "training"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TrainingResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Delete a trained model</summary> /// <param name="data">mybucket/mydata resource in Google Storage</param> public virtual DeleteRequest Delete(string data) { return new DeleteRequest(service, data); } /// <summary>Delete a trained model</summary> public class DeleteRequest : PredictionBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string data) : base(service) { Data = data; InitParameters(); } /// <summary>mybucket/mydata resource in Google Storage</summary> [Google.Apis.Util.RequestParameterAttribute("data", Google.Apis.Util.RequestParameterType.Path)] public virtual string Data { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "training/{data}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "data", new Google.Apis.Discovery.Parameter { Name = "data", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Check training status of your model</summary> /// <param name="data">mybucket/mydata resource in Google Storage</param> public virtual GetRequest Get(string data) { return new GetRequest(service, data); } /// <summary>Check training status of your model</summary> public class GetRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_3.Data.Training> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string data) : base(service) { Data = data; InitParameters(); } /// <summary>mybucket/mydata resource in Google Storage</summary> [Google.Apis.Util.RequestParameterAttribute("data", Google.Apis.Util.RequestParameterType.Path)] public virtual string Data { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "training/{data}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "data", new Google.Apis.Discovery.Parameter { Name = "data", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Begin training your model</summary> /// <param name="body">The body of the request.</param> public virtual InsertRequest Insert(Google.Apis.Prediction.v1_3.Data.Training body) { return new InsertRequest(service, body); } /// <summary>Begin training your model</summary> public class InsertRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_3.Data.Training> { /// <summary>Constructs a new Insert request.</summary> public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_3.Data.Training body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_3.Data.Training Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "insert"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "training"; } } /// <summary>Initializes Insert parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Submit data and request a prediction</summary> /// <param name="body">The body of the request.</param> /// <param name="data">mybucket/mydata resource in Google Storage</param> public virtual PredictRequest Predict(Google.Apis.Prediction.v1_3.Data.Input body, string data) { return new PredictRequest(service, body, data); } /// <summary>Submit data and request a prediction</summary> public class PredictRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_3.Data.Output> { /// <summary>Constructs a new Predict request.</summary> public PredictRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_3.Data.Input body, string data) : base(service) { Data = data; Body = body; InitParameters(); } /// <summary>mybucket/mydata resource in Google Storage</summary> [Google.Apis.Util.RequestParameterAttribute("data", Google.Apis.Util.RequestParameterType.Path)] public virtual string Data { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_3.Data.Input Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "predict"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "training/{data}/predict"; } } /// <summary>Initializes Predict parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "data", new Google.Apis.Discovery.Parameter { Name = "data", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Add new data to a trained model</summary> /// <param name="body">The body of the request.</param> /// <param name="data">mybucket/mydata resource in Google Storage</param> public virtual UpdateRequest Update(Google.Apis.Prediction.v1_3.Data.Update body, string data) { return new UpdateRequest(service, body, data); } /// <summary>Add new data to a trained model</summary> public class UpdateRequest : PredictionBaseServiceRequest<Google.Apis.Prediction.v1_3.Data.Training> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Prediction.v1_3.Data.Update body, string data) : base(service) { Data = data; Body = body; InitParameters(); } /// <summary>mybucket/mydata resource in Google Storage</summary> [Google.Apis.Util.RequestParameterAttribute("data", Google.Apis.Util.RequestParameterType.Path)] public virtual string Data { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Prediction.v1_3.Data.Update Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "update"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PUT"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "training/{data}"; } } /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "data", new Google.Apis.Discovery.Parameter { Name = "data", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Prediction.v1_3.Data { public class Input : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Input to the model for a prediction</summary> [Newtonsoft.Json.JsonPropertyAttribute("input")] public virtual Input.InputData InputValue { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Input to the model for a prediction</summary> public class InputData { /// <summary>A list of input features, these can be strings or doubles.</summary> [Newtonsoft.Json.JsonPropertyAttribute("csvInstance")] public virtual System.Collections.Generic.IList<object> CsvInstance { get; set; } } } public class Output : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The unique name for the predictive model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>What kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The most likely class [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputLabel")] public virtual string OutputLabel { get; set; } /// <summary>A list of classes with their estimated probabilities [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputMulti")] public virtual System.Collections.Generic.IList<Output.OutputMultiData> OutputMulti { get; set; } /// <summary>The estimated regression value [Regression models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("outputValue")] public virtual System.Nullable<double> OutputValue { get; set; } /// <summary>A URL to re-request this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } public class OutputMultiData { /// <summary>The class label.</summary> [Newtonsoft.Json.JsonPropertyAttribute("label")] public virtual string Label { get; set; } /// <summary>The probability of the class.</summary> [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual System.Nullable<double> Score { get; set; } } } public class Training : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The unique name for the predictive model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>What kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Model metadata.</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelInfo")] public virtual Training.ModelInfoData ModelInfo { get; set; } /// <summary>A URL to re-request this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>The current status of the training job. This can be one of following: RUNNING; DONE; ERROR; ERROR: /// TRAINING JOB NOT FOUND</summary> [Newtonsoft.Json.JsonPropertyAttribute("trainingStatus")] public virtual string TrainingStatus { get; set; } /// <summary>A class weighting function, which allows the importance weights for classes to be specified /// [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("utility")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,System.Nullable<double>>> Utility { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Model metadata.</summary> public class ModelInfoData { /// <summary>Estimated accuracy of model taking utility weights into account [Categorical models /// only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("classWeightedAccuracy")] public virtual System.Nullable<double> ClassWeightedAccuracy { get; set; } /// <summary>A number between 0.0 and 1.0, where 1.0 is 100% accurate. This is an estimate, based on the /// amount and quality of the training data, of the estimated prediction accuracy. You can use this is a /// guide to decide whether the results are accurate enough for your needs. This estimate will be more /// reliable if your real input data is similar to your training data [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("classificationAccuracy")] public virtual System.Nullable<double> ClassificationAccuracy { get; set; } /// <summary>An output confusion matrix. This shows an estimate for how this model will do in predictions. /// This is first indexed by the true class label. For each true class label, this provides a pair /// {predicted_label, count}, where count is the estimated number of times the model will predict the /// predicted label given the true label. Will not output if more then 100 classes [Categorical models /// only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("confusionMatrix")] public virtual System.Collections.Generic.IDictionary<string,System.Collections.Generic.IDictionary<string,System.Nullable<double>>> ConfusionMatrix { get; set; } /// <summary>A list of the confusion matrix row totals</summary> [Newtonsoft.Json.JsonPropertyAttribute("confusionMatrixRowTotals")] public virtual System.Collections.Generic.IDictionary<string,System.Nullable<double>> ConfusionMatrixRowTotals { get; set; } /// <summary>An estimated mean squared error. The can be used to measure the quality of the predicted model /// [Regression models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("meanSquaredError")] public virtual System.Nullable<double> MeanSquaredError { get; set; } /// <summary>Type of predictive model (CLASSIFICATION or REGRESSION)</summary> [Newtonsoft.Json.JsonPropertyAttribute("modelType")] public virtual string ModelType { get; set; } /// <summary>Number of classes in the trained model [Categorical models only].</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberClasses")] public virtual System.Nullable<long> NumberClasses { get; set; } /// <summary>Number of valid data instances used in the trained model.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberInstances")] public virtual System.Nullable<long> NumberInstances { get; set; } } } public class Update : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The true class label of this instance</summary> [Newtonsoft.Json.JsonPropertyAttribute("classLabel")] public virtual string ClassLabel { get; set; } /// <summary>The input features for this instance</summary> [Newtonsoft.Json.JsonPropertyAttribute("csvInstance")] public virtual System.Collections.Generic.IList<object> CsvInstance { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcatQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Concatenates one data source with another. Order preservation is used to ensure /// the output is actually a concatenation -- i.e. one after the other. The only /// special synchronization required is to find the largest index N in the first data /// source so that the indices of elements in the second data source can be offset /// by adding N+1. This makes it appear to the order preservation infrastructure as /// though all elements in the second came after all elements in the first, which is /// precisely what we want. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class ConcatQueryOperator<TSource> : BinaryQueryOperator<TSource, TSource, TSource> { private readonly bool _prematureMergeLeft = false; // Whether to prematurely merge the left data source private readonly bool _prematureMergeRight = false; // Whether to prematurely merge the right data source //--------------------------------------------------------------------------------------- // Initializes a new concatenation operator. // // Arguments: // child - the child whose data we will reverse // internal ConcatQueryOperator(ParallelQuery<TSource> firstChild, ParallelQuery<TSource> secondChild) : base(firstChild, secondChild) { Debug.Assert(firstChild != null, "first child data source cannot be null"); Debug.Assert(secondChild != null, "second child data source cannot be null"); _outputOrdered = LeftChild.OutputOrdered || RightChild.OutputOrdered; _prematureMergeLeft = LeftChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); _prematureMergeRight = RightChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); if ((LeftChild.OrdinalIndexState == OrdinalIndexState.Indexable) && (RightChild.OrdinalIndexState == OrdinalIndexState.Indexable)) { SetOrdinalIndex(OrdinalIndexState.Indexable); } else { SetOrdinalIndex( ExchangeUtilities.Worse(OrdinalIndexState.Increasing, ExchangeUtilities.Worse(LeftChild.OrdinalIndexState, RightChild.OrdinalIndexState))); } } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { // We just open the children operators. QueryResults<TSource> leftChildResults = LeftChild.Open(settings, preferStriping); QueryResults<TSource> rightChildResults = RightChild.Open(settings, preferStriping); return ConcatQueryOperatorResults.NewResults(leftChildResults, rightChildResults, this, settings, preferStriping); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStream, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, bool preferStriping, QuerySettings settings) { // Prematurely merge the left results, if necessary if (_prematureMergeLeft) { ListQueryResults<TSource> leftStreamResults = ExecuteAndCollectResults(leftStream, leftStream.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> leftStreamInc = leftStreamResults.GetPartitionedStream(); WrapHelper<int, TRightKey>(leftStreamInc, rightStream, outputRecipient, settings, preferStriping); } else { Debug.Assert(!ExchangeUtilities.IsWorseThan(leftStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper<TLeftKey, TRightKey>(leftStream, rightStream, outputRecipient, settings, preferStriping); } } private void WrapHelper<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, QuerySettings settings, bool preferStriping) { // Prematurely merge the right results, if necessary if (_prematureMergeRight) { ListQueryResults<TSource> rightStreamResults = ExecuteAndCollectResults(rightStream, leftStreamInc.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> rightStreamInc = rightStreamResults.GetPartitionedStream(); WrapHelper2<TLeftKey, int>(leftStreamInc, rightStreamInc, outputRecipient); } else { Debug.Assert(!ExchangeUtilities.IsWorseThan(rightStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper2<TLeftKey, TRightKey>(leftStreamInc, rightStream, outputRecipient); } } private void WrapHelper2<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStreamInc, IPartitionedStreamRecipient<TSource> outputRecipient) { int partitionCount = leftStreamInc.PartitionCount; // Generate the shared data. IComparer<ConcatKey<TLeftKey, TRightKey>> comparer = ConcatKey<TLeftKey, TRightKey>.MakeComparer( leftStreamInc.KeyComparer, rightStreamInc.KeyComparer); var outputStream = new PartitionedStream<TSource, ConcatKey<TLeftKey, TRightKey>>(partitionCount, comparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ConcatQueryOperatorEnumerator<TLeftKey, TRightKey>(leftStreamInc[i], rightStreamInc[i]); } outputRecipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { return LeftChild.AsSequentialQuery(token).Concat(RightChild.AsSequentialQuery(token)); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for concatenating two data sources. // sealed class ConcatQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TSource, ConcatKey<TLeftKey, TRightKey>> { private QueryOperatorEnumerator<TSource, TLeftKey> _firstSource; // The first data source to enumerate. private QueryOperatorEnumerator<TSource, TRightKey> _secondSource; // The second data source to enumerate. private bool _begunSecond; // Whether this partition has begun enumerating the second source yet. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal ConcatQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TLeftKey> firstSource, QueryOperatorEnumerator<TSource, TRightKey> secondSource) { Debug.Assert(firstSource != null); Debug.Assert(secondSource != null); _firstSource = firstSource; _secondSource = secondSource; } //--------------------------------------------------------------------------------------- // MoveNext advances to the next element in the output. While the first data source has // elements, this consists of just advancing through it. After this, all partitions must // synchronize at a barrier and publish the maximum index N. Finally, all partitions can // move on to the second data source, adding N+1 to indices in order to get the correct // index offset. // internal override bool MoveNext(ref TSource currentElement, ref ConcatKey<TLeftKey, TRightKey> currentKey) { Debug.Assert(_firstSource != null); Debug.Assert(_secondSource != null); // If we are still enumerating the first source, fetch the next item. if (!_begunSecond) { // If elements remain, just return true and continue enumerating the left. TLeftKey leftKey = default(TLeftKey); if (_firstSource.MoveNext(ref currentElement, ref leftKey)) { currentKey = ConcatKey<TLeftKey, TRightKey>.MakeLeft(leftKey); return true; } _begunSecond = true; } // Now either move on to, or continue, enumerating the right data source. TRightKey rightKey = default(TRightKey); if (_secondSource.MoveNext(ref currentElement, ref rightKey)) { currentKey = ConcatKey<TLeftKey, TRightKey>.MakeRight(rightKey); return true; } return false; } protected override void Dispose(bool disposing) { _firstSource.Dispose(); _secondSource.Dispose(); } } //----------------------------------------------------------------------------------- // Query results for a Concat operator. The results are indexable if the child // results were indexable. // class ConcatQueryOperatorResults : BinaryQueryOperatorResults { private int _leftChildCount; // The number of elements in the left child result set private int _rightChildCount; // The number of elements in the right child result set public static QueryResults<TSource> NewResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> op, QuerySettings settings, bool preferStriping) { if (leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible) { return new ConcatQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } else { return new BinaryQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } } private ConcatQueryOperatorResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> concatOp, QuerySettings settings, bool preferStriping) : base(leftChildQueryResults, rightChildQueryResults, concatOp, settings, preferStriping) { Debug.Assert(leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible); _leftChildCount = leftChildQueryResults.ElementsCount; _rightChildCount = rightChildQueryResults.ElementsCount; } internal override bool IsIndexible { get { return true; } } internal override int ElementsCount { get { Debug.Assert(_leftChildCount >= 0 && _rightChildCount >= 0); return _leftChildCount + _rightChildCount; } } internal override TSource GetElement(int index) { if (index < _leftChildCount) { return _leftChildQueryResults.GetElement(index); } else { return _rightChildQueryResults.GetElement(index - _leftChildCount); } } } } //--------------------------------------------------------------------------------------- // ConcatKey represents an ordering key for the Concat operator. It knows whether the // element it is associated with is from the left source or the right source, and also // the elements ordering key. // internal struct ConcatKey<TLeftKey, TRightKey> { private readonly TLeftKey _leftKey; private readonly TRightKey _rightKey; private readonly bool _isLeft; private ConcatKey(TLeftKey leftKey, TRightKey rightKey, bool isLeft) { _leftKey = leftKey; _rightKey = rightKey; _isLeft = isLeft; } internal static ConcatKey<TLeftKey, TRightKey> MakeLeft(TLeftKey leftKey) { return new ConcatKey<TLeftKey, TRightKey>(leftKey, default(TRightKey), isLeft: true); } internal static ConcatKey<TLeftKey, TRightKey> MakeRight(TRightKey rightKey) { return new ConcatKey<TLeftKey, TRightKey>(default(TLeftKey), rightKey, isLeft: false); } internal static IComparer<ConcatKey<TLeftKey, TRightKey>> MakeComparer( IComparer<TLeftKey> leftComparer, IComparer<TRightKey> rightComparer) { return new ConcatKeyComparer(leftComparer, rightComparer); } //--------------------------------------------------------------------------------------- // ConcatKeyComparer compares ConcatKeys, so that elements from the left source come // before elements from the right source, and elements within each source are ordered // according to the corresponding order key. // private class ConcatKeyComparer : IComparer<ConcatKey<TLeftKey, TRightKey>> { private IComparer<TLeftKey> _leftComparer; private IComparer<TRightKey> _rightComparer; internal ConcatKeyComparer(IComparer<TLeftKey> leftComparer, IComparer<TRightKey> rightComparer) { _leftComparer = leftComparer; _rightComparer = rightComparer; } public int Compare(ConcatKey<TLeftKey, TRightKey> x, ConcatKey<TLeftKey, TRightKey> y) { // If one element is from the left source and the other not, the element from the left source // comes earlier. if (x._isLeft != y._isLeft) { return x._isLeft ? -1 : 1; } // Elements are from the same source (left or right). Compare the corresponding keys. if (x._isLeft) { return _leftComparer.Compare(x._leftKey, y._leftKey); } return _rightComparer.Compare(x._rightKey, y._rightKey); } } } }
// 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.ComponentModel; using System.Data.ProviderBase; using System.Diagnostics; namespace System.Data.Common { internal sealed class DataRecordInternal : DbDataRecord, ICustomTypeDescriptor { private SchemaInfo[] _schemaInfo; private object[] _values; private PropertyDescriptorCollection _propertyDescriptors; private FieldNameLookup _fieldNameLookup; // copy all runtime data information internal DataRecordInternal(SchemaInfo[] schemaInfo, object[] values, PropertyDescriptorCollection descriptors, FieldNameLookup fieldNameLookup) { Debug.Assert(null != schemaInfo, "invalid attempt to instantiate DataRecordInternal with null schema information"); Debug.Assert(null != values, "invalid attempt to instantiate DataRecordInternal with null value[]"); _schemaInfo = schemaInfo; _values = values; _propertyDescriptors = descriptors; _fieldNameLookup = fieldNameLookup; } // copy all runtime data information internal DataRecordInternal(object[] values, PropertyDescriptorCollection descriptors, FieldNameLookup fieldNameLookup) { Debug.Assert(null != values, "invalid attempt to instantiate DataRecordInternal with null value[]"); _values = values; _propertyDescriptors = descriptors; _fieldNameLookup = fieldNameLookup; } internal void SetSchemaInfo(SchemaInfo[] schemaInfo) { Debug.Assert(null == _schemaInfo, "invalid attempt to override DataRecordInternal schema information"); _schemaInfo = schemaInfo; } public override int FieldCount { get { return _schemaInfo.Length; } } public override int GetValues(object[] values) { if (null == values) { throw ADP.ArgumentNull(nameof(values)); } int copyLen = (values.Length < _schemaInfo.Length) ? values.Length : _schemaInfo.Length; for (int i = 0; i < copyLen; i++) { values[i] = _values[i]; } return copyLen; } public override string GetName(int i) { return _schemaInfo[i].name; } public override object GetValue(int i) { return _values[i]; } public override string GetDataTypeName(int i) { return _schemaInfo[i].typeName; } public override Type GetFieldType(int i) { return _schemaInfo[i].type; } public override int GetOrdinal(string name) { return _fieldNameLookup.GetOrdinal(name); } public override object this[int i] { get { return GetValue(i); } } public override object this[string name] { get { return GetValue(GetOrdinal(name)); } } public override bool GetBoolean(int i) { return ((bool)_values[i]); } public override byte GetByte(int i) { return ((byte)_values[i]); } public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { int cbytes = 0; int ndataIndex; byte[] data = (byte[])_values[i]; cbytes = data.Length; // since arrays can't handle 64 bit values and this interface doesn't // allow chunked access to data, a dataIndex outside the rang of Int32 // is invalid if (dataIndex > int.MaxValue) { throw ADP.InvalidSourceBufferIndex(cbytes, dataIndex, nameof(dataIndex)); } ndataIndex = (int)dataIndex; // if no buffer is passed in, return the number of characters we have if (null == buffer) return cbytes; try { if (ndataIndex < cbytes) { // help the user out in the case where there's less data than requested if ((ndataIndex + length) > cbytes) cbytes = cbytes - ndataIndex; else cbytes = length; } // until arrays are 64 bit, we have to do these casts Array.Copy(data, ndataIndex, buffer, bufferIndex, cbytes); } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { cbytes = data.Length; if (length < 0) { throw ADP.InvalidDataLength(length); } // if bad buffer index, throw if (bufferIndex < 0 || bufferIndex >= buffer.Length) { throw ADP.InvalidDestinationBufferIndex(length, bufferIndex, nameof(bufferIndex)); } // if bad data index, throw if (dataIndex < 0 || dataIndex >= cbytes) { throw ADP.InvalidSourceBufferIndex(length, dataIndex, nameof(dataIndex)); } // if there is not enough room in the buffer for data if (cbytes + bufferIndex > buffer.Length) { throw ADP.InvalidBufferSizeOrIndex(cbytes, bufferIndex); } } return cbytes; } public override char GetChar(int i) => ((string)_values[i])[0]; public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) { // if the object doesn't contain a char[] then the user will get an exception string s = (string)_values[i]; char[] data = s.ToCharArray(); int cchars = data.Length; // since arrays can't handle 64 bit values and this interface doesn't // allow chunked access to data, a dataIndex outside the rang of Int32 // is invalid if (dataIndex > int.MaxValue) { throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, nameof(dataIndex)); } int ndataIndex = (int)dataIndex; // if no buffer is passed in, return the number of characters we have if (null == buffer) { return cchars; } try { if (ndataIndex < cchars) { // help the user out in the case where there's less data than requested if ((ndataIndex + length) > cchars) { cchars = cchars - ndataIndex; } else { cchars = length; } } Array.Copy(data, ndataIndex, buffer, bufferIndex, cchars); } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { cchars = data.Length; if (length < 0) { throw ADP.InvalidDataLength(length); } // if bad buffer index, throw if (bufferIndex < 0 || bufferIndex >= buffer.Length) { throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, nameof(bufferIndex)); } // if bad data index, throw if (ndataIndex < 0 || ndataIndex >= cchars) { throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, nameof(dataIndex)); } // if there is not enough room in the buffer for data if (cchars + bufferIndex > buffer.Length) { throw ADP.InvalidBufferSizeOrIndex(cchars, bufferIndex); } } return cchars; } public override Guid GetGuid(int i) { return ((Guid)_values[i]); } public override short GetInt16(int i) { return ((short)_values[i]); } public override int GetInt32(int i) { return ((int)_values[i]); } public override long GetInt64(int i) { return ((long)_values[i]); } public override float GetFloat(int i) { return ((float)_values[i]); } public override double GetDouble(int i) { return ((double)_values[i]); } public override string GetString(int i) { return ((string)_values[i]); } public override decimal GetDecimal(int i) { return ((decimal)_values[i]); } public override DateTime GetDateTime(int i) { return ((DateTime)_values[i]); } public override bool IsDBNull(int i) { object o = _values[i]; return (null == o || Convert.IsDBNull(o)); } // // ICustomTypeDescriptor // AttributeCollection ICustomTypeDescriptor.GetAttributes() { return new AttributeCollection(null); } string ICustomTypeDescriptor.GetClassName() { return null; } string ICustomTypeDescriptor.GetComponentName() { return null; } TypeConverter ICustomTypeDescriptor.GetConverter() { return null; } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return new EventDescriptorCollection(null); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return new EventDescriptorCollection(null); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(null); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { if (_propertyDescriptors == null) { _propertyDescriptors = new PropertyDescriptorCollection(null); } return _propertyDescriptors; } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } } // this doesn't change per record, only alloc once internal struct SchemaInfo { public string name; public string typeName; public Type type; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers { /// <summary> /// An <see cref="IHtmlContentBuilder"/> that is backed by a buffer provided by <see cref="IViewBufferScope"/>. /// </summary> [DebuggerDisplay("{DebuggerToString()}")] internal class ViewBuffer : IHtmlContentBuilder { public const int PartialViewPageSize = 32; public const int TagHelperPageSize = 32; public const int ViewComponentPageSize = 32; public const int ViewPageSize = 256; private readonly IViewBufferScope _bufferScope; private readonly string _name; private readonly int _pageSize; private ViewBufferPage _currentPage; // Limits allocation if the ViewBuffer has only one page (frequent case). private List<ViewBufferPage> _multiplePages; // Allocated only if necessary /// <summary> /// Initializes a new instance of <see cref="ViewBuffer"/>. /// </summary> /// <param name="bufferScope">The <see cref="IViewBufferScope"/>.</param> /// <param name="name">A name to identify this instance.</param> /// <param name="pageSize">The size of buffer pages.</param> public ViewBuffer(IViewBufferScope bufferScope, string name, int pageSize) { if (bufferScope == null) { throw new ArgumentNullException(nameof(bufferScope)); } if (pageSize <= 0) { throw new ArgumentOutOfRangeException(nameof(pageSize)); } _bufferScope = bufferScope; _name = name; _pageSize = pageSize; } /// <summary> /// Get the <see cref="ViewBufferPage"/> count. /// </summary> public int Count { get { if (_multiplePages != null) { return _multiplePages.Count; } if (_currentPage != null) { return 1; } return 0; } } /// <summary> /// Gets a <see cref="ViewBufferPage"/>. /// </summary> public ViewBufferPage this[int index] { get { if (_multiplePages != null) { return _multiplePages[index]; } if (index == 0 && _currentPage != null) { return _currentPage; } throw new IndexOutOfRangeException(); } } /// <inheritdoc /> // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339 [MethodImpl(MethodImplOptions.AggressiveInlining)] public IHtmlContentBuilder Append(string unencoded) { if (unencoded != null) { // Text that needs encoding is the uncommon case in views, which is why it // creates a wrapper and pre-encoded text does not. AppendValue(new ViewBufferValue(new EncodingWrapper(unencoded))); } return this; } /// <inheritdoc /> // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339 [MethodImpl(MethodImplOptions.AggressiveInlining)] public IHtmlContentBuilder AppendHtml(IHtmlContent content) { if (content != null) { AppendValue(new ViewBufferValue(content)); } return this; } /// <inheritdoc /> // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339 [MethodImpl(MethodImplOptions.AggressiveInlining)] public IHtmlContentBuilder AppendHtml(string encoded) { if (encoded != null) { AppendValue(new ViewBufferValue(encoded)); } return this; } // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339 [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendValue(ViewBufferValue value) { var page = GetCurrentPage(); page.Append(value); } // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339 [MethodImpl(MethodImplOptions.AggressiveInlining)] private ViewBufferPage GetCurrentPage() { var currentPage = _currentPage; if (currentPage == null || currentPage.IsFull) { // Uncommon slow-path return AppendNewPage(); } return currentPage; } // Slow path for above, don't inline [MethodImpl(MethodImplOptions.NoInlining)] private ViewBufferPage AppendNewPage() { AddPage(new ViewBufferPage(_bufferScope.GetPage(_pageSize))); return _currentPage; } private void AddPage(ViewBufferPage page) { if (_multiplePages != null) { _multiplePages.Add(page); } else if (_currentPage != null) { _multiplePages = new List<ViewBufferPage>(2); _multiplePages.Add(_currentPage); _multiplePages.Add(page); } _currentPage = page; } /// <inheritdoc /> public IHtmlContentBuilder Clear() { _multiplePages = null; _currentPage = null; return this; } /// <inheritdoc /> public void WriteTo(TextWriter writer, HtmlEncoder encoder) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (encoder == null) { throw new ArgumentNullException(nameof(encoder)); } for (var i = 0; i < Count; i++) { var page = this[i]; for (var j = 0; j < page.Count; j++) { var value = page.Buffer[j]; if (value.Value is string valueAsString) { writer.Write(valueAsString); continue; } if (value.Value is IHtmlContent valueAsHtmlContent) { valueAsHtmlContent.WriteTo(writer, encoder); continue; } } } } /// <summary> /// Writes the buffered content to <paramref name="writer"/>. /// </summary> /// <param name="writer">The <see cref="TextWriter"/>.</param> /// <param name="encoder">The <see cref="HtmlEncoder"/>.</param> /// <returns>A <see cref="Task"/> which will complete once content has been written.</returns> public async Task WriteToAsync(TextWriter writer, HtmlEncoder encoder) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (encoder == null) { throw new ArgumentNullException(nameof(encoder)); } for (var i = 0; i < Count; i++) { var page = this[i]; for (var j = 0; j < page.Count; j++) { var value = page.Buffer[j]; if (value.Value is string valueAsString) { await writer.WriteAsync(valueAsString); continue; } if (value.Value is ViewBuffer valueAsViewBuffer) { await valueAsViewBuffer.WriteToAsync(writer, encoder); continue; } if (value.Value is IHtmlContent valueAsHtmlContent) { valueAsHtmlContent.WriteTo(writer, encoder); await writer.FlushAsync(); continue; } } } } private string DebuggerToString() => _name; public void CopyTo(IHtmlContentBuilder destination) { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } for (var i = 0; i < Count; i++) { var page = this[i]; for (var j = 0; j < page.Count; j++) { var value = page.Buffer[j]; string valueAsString; IHtmlContentContainer valueAsContainer; if ((valueAsString = value.Value as string) != null) { destination.AppendHtml(valueAsString); } else if ((valueAsContainer = value.Value as IHtmlContentContainer) != null) { valueAsContainer.CopyTo(destination); } else { destination.AppendHtml((IHtmlContent)value.Value); } } } } public void MoveTo(IHtmlContentBuilder destination) { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } // Perf: We have an efficient implementation when the destination is another view buffer, // we can just insert our pages as-is. if (destination is ViewBuffer other) { MoveTo(other); return; } for (var i = 0; i < Count; i++) { var page = this[i]; for (var j = 0; j < page.Count; j++) { var value = page.Buffer[j]; string valueAsString; IHtmlContentContainer valueAsContainer; if ((valueAsString = value.Value as string) != null) { destination.AppendHtml(valueAsString); } else if ((valueAsContainer = value.Value as IHtmlContentContainer) != null) { valueAsContainer.MoveTo(destination); } else { destination.AppendHtml((IHtmlContent)value.Value); } } } for (var i = 0; i < Count; i++) { var page = this[i]; Array.Clear(page.Buffer, 0, page.Count); _bufferScope.ReturnSegment(page.Buffer); } Clear(); } private void MoveTo(ViewBuffer destination) { for (var i = 0; i < Count; i++) { var page = this[i]; var destinationPage = destination.Count == 0 ? null : destination[destination.Count - 1]; // If the source page is less or equal to than half full, let's copy it's content to the destination // page if possible. var isLessThanHalfFull = 2 * page.Count <= page.Capacity; if (isLessThanHalfFull && destinationPage != null && destinationPage.Capacity - destinationPage.Count >= page.Count) { // We have room, let's copy the items. Array.Copy( sourceArray: page.Buffer, sourceIndex: 0, destinationArray: destinationPage.Buffer, destinationIndex: destinationPage.Count, length: page.Count); destinationPage.Count += page.Count; // Now we can return the source page, and it can be reused in the scope of this request. Array.Clear(page.Buffer, 0, page.Count); _bufferScope.ReturnSegment(page.Buffer); } else { // Otherwise, let's just add the source page to the other buffer. destination.AddPage(page); } } Clear(); } private class EncodingWrapper : IHtmlContent { private readonly string _unencoded; public EncodingWrapper(string unencoded) { _unencoded = unencoded; } public void WriteTo(TextWriter writer, HtmlEncoder encoder) { encoder.Encode(writer, _unencoded); } } } }
/**************************************************************************** | | Copyright (c) 2007 Novell, Inc. | All Rights Reserved. | | This program is free software; you can redistribute it and/or | modify it under the terms of version 2 of the GNU General Public License as | published by the Free Software Foundation. | | This program is distributed in the hope that it will be useful, | but WITHOUT ANY WARRANTY; without even the implied warranty of | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | GNU General Public License for more details. | | You should have received a copy of the GNU General Public License | along with this program; if not, contact Novell, Inc. | | To contact Novell about this file by physical or electronic mail, | you may find current contact information at www.novell.com | | Author: Russ Young | Thanks to: Bruce Schneier / Counterpane Labs | for the Blowfish encryption algorithm and | reference implementation. http://www.schneier.com/blowfish.html |***************************************************************************/ using System; using System.Text; using System.IO; namespace Simias.Encryption { /// <summary> /// Class that provides blowfish encryption. /// </summary> public class Blowfish { const int N = 16; const int KEYBYTES = 8; static uint[] _P = { 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b }; static uint[,] _S = { { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a }, { 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 }, { 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 }, { 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 } }; uint[] P; uint[,] S; /// <summary> /// Constructs and initializes a blowfish instance with the supplied key. /// </summary> /// <param name="key">The key to cipher with.</param> public Blowfish(byte[] key) { short i; short j; short k; uint data; uint datal; uint datar; P = _P.Clone() as uint[]; S = _S.Clone() as uint[,]; j = 0; for (i = 0; i < N + 2; ++i) { data = 0x00000000; for (k = 0; k < 4; ++k) { data = (data << 8) | key[j]; j++; if (j >= key.Length) { j = 0; } } P[i] = P[i] ^ data; } datal = 0x00000000; datar = 0x00000000; for (i = 0; i < N + 2; i += 2) { Encipher(ref datal, ref datar); P[i] = datal; P[i + 1] = datar; } for (i = 0; i < 4; ++i) { for (j = 0; j < 256; j += 2) { Encipher(ref datal, ref datar); S[i,j] = datal; S[i,j + 1] = datar; } } } /// <summary> /// /// </summary> /// <param name="x"></param> /// <returns></returns> private uint F(uint x) { ushort a; ushort b; ushort c; ushort d; uint y; d = (ushort)(x & 0x00FF); x >>= 8; c = (ushort)(x & 0x00FF); x >>= 8; b = (ushort)(x & 0x00FF); x >>= 8; a = (ushort)(x & 0x00FF); //y = ((S[0][a] + S[1][b]) ^ S[2][c]) + S[3][d]; y = S[0,a] + S[1,b]; y = y ^ S[2,c]; y = y + S[3,d]; return y; } /// <summary> /// Encrypts a byte array in place. /// </summary> /// <param name="data">The array to encrypt.</param> /// <param name="length">The amount to encrypt.</param> public void Encipher(byte[] data, int length) { uint xl, xr; if ((length % 8) != 0) throw new Exception("Invalid Length"); for (int i = 0; i < length; i+=8) { // Encode the data in 8 byte blocks. xl = (uint)((data[i] << 24) | (data[i+1] << 16) | (data[i+2] << 8) | data[i+3]); xr = (uint)((data[i+4] << 24) | (data[i+5] << 16) | (data[i+6] << 8) | data[i+7]); Encipher(ref xl, ref xr); // Now Replace the data. data[i] = (byte)(xl >> 24); data[i+1] = (byte)(xl >> 16); data[i+2] = (byte)(xl >> 8); data[i+3] = (byte)(xl); data[i+4] = (byte)(xr >> 24); data[i+5] = (byte)(xr >> 16); data[i+6] = (byte)(xr >> 8); data[i+7] = (byte)(xr);} } /// <summary> /// Encrypts 8 bytes of data (1 block) /// </summary> /// <param name="xl">The left part of the 8 bytes.</param> /// <param name="xr">The right part of the 8 bytes.</param> private void Encipher(ref uint xl, ref uint xr) { uint Xl; uint Xr; uint temp; short i; Xl = xl; Xr = xr; for (i = 0; i < N; ++i) { Xl = Xl ^ P[i]; Xr = F(Xl) ^ Xr; temp = Xl; Xl = Xr; Xr = temp; } temp = Xl; Xl = Xr; Xr = temp; Xr = Xr ^ P[N]; Xl = Xl ^ P[N + 1]; xl = Xl; xr = Xr; } /// <summary> /// Decrypts a byte array in place. /// </summary> /// <param name="data">The array to decrypt.</param> /// <param name="length">The amount to decrypt.</param> public void Decipher(byte[] data, int length) { uint xl, xr; if ((length % 8) != 0) throw new Exception("Invalid Length"); for (int i = 0; i < length; i += 8) { // Encode the data in 8 byte blocks. xl = (uint)(data[i] | (data[i+1] << 8) | (data[i+2] << 16) | (data[i+3] << 24)); xr = (uint)(data[i+4] | (data[i+5] << 8) | (data[i+6] << 16) | (data[i+7] << 24)); Decipher(ref xl, ref xr); // Now Replace the data. data[i] = (byte)(xl); data[i+1] = (byte)(xl >> 8); data[i+2] = (byte)(xl >> 16); data[i+3] = (byte)(xl >> 24); data[i+4] = (byte)(xr); data[i+5] = (byte)(xr >> 8); data[i+6] = (byte)(xr >> 16); data[i+7] = (byte)(xr >> 24); } } /// <summary> /// Decrypts 8 bytes of data (1 block) /// </summary> /// <param name="xl">The left part of the 8 bytes.</param> /// <param name="xr">The right part of the 8 bytes.</param> public void Decipher(ref uint xl, ref uint xr) { uint Xl; uint Xr; uint temp; short i; Xl = xl; Xr = xr; for (i = N + 1; i > 1; --i) { Xl = Xl ^ P[i]; Xr = F(Xl) ^ Xr; /* Exchange Xl and Xr */ temp = Xl; Xl = Xr; Xr = temp; } /* Exchange Xl and Xr */ temp = Xl; Xl = Xr; Xr = temp; Xr = Xr ^ P[1]; Xl = Xl ^ P[0]; xl = Xl; xr = Xr; } } public class BlowfishStream : Stream { class CBState : IAsyncResult { internal AsyncCallback callback; internal object state; internal byte[] buffer; internal IAsyncResult result; internal CBState(AsyncCallback callback, object state, byte[] buffer) { this.callback = callback; this.state = state; this.buffer = buffer; } #region IAsyncResult Members public object AsyncState { get { return state; } } public bool CompletedSynchronously { get { return result.CompletedSynchronously; } } public System.Threading.WaitHandle AsyncWaitHandle { get { return result.AsyncWaitHandle; } } public bool IsCompleted { get { return result.IsCompleted; } } #endregion } public enum Target { Encrypted, Normal }; Stream stream; Blowfish bf; Target target; BlowfishStream(Stream stream, Blowfish bf, Target target) { this.stream = stream; this.bf = bf; this.target = target; } /// <summary> /// Returns true if the stream support reads. /// </summary> public override bool CanRead { get {return stream.CanRead;} } /// <summary> /// Returns true is the stream supports seeks. /// </summary> public override bool CanSeek { get {return stream.CanSeek;} } /// <summary> /// Returns true if the stream supports writes. /// </summary> public override bool CanWrite { get {return stream.CanWrite;} } /// <summary> /// Returns the length of the stream. /// </summary> public override long Length { get {return stream.Length;} } /// <summary> /// Gets or Sets the posistion of the stream. /// </summary> public override long Position { get {return stream.Position;} set {stream.Position = value;} } /// <summary> /// Flushes the stream. /// </summary> public override void Flush() { stream.Flush(); } /// <summary> /// Read data from the stream and encrypt it. /// </summary> /// <param name="buffer">The buffer to read into.</param> /// <param name="offset">The offset in the buffer to begin storing data.</param> /// <param name="count">The number of bytes to read.</param> /// <returns></returns> public override int Read(byte[] buffer, int offset, int count) { int bytesRead = stream.Read(buffer, offset, count); if (target == Target.Normal) bf.Encipher(buffer, bytesRead); else bf.Decipher(buffer, bytesRead); return bytesRead; } /// <summary> /// Write data to the stream after decrypting it. /// </summary> /// <param name="buffer">The buffer containing the data to write.</param> /// <param name="offset">The offset in the buffer where the data begins.</param> /// <param name="count">The number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (target == Target.Normal) bf.Decipher(buffer, count); else bf.Encipher(buffer, count); stream.Write(buffer, offset, count); } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { CBState cbs = new CBState(callback, state, buffer); cbs.result = base.BeginRead (buffer, offset, count, new AsyncCallback(ReadComplete), cbs); return cbs; } /// <summary> /// /// </summary> /// <param name="asyncResult"></param> /// <returns></returns> public override int EndRead(IAsyncResult asyncResult) { CBState cbs = (CBState)asyncResult.AsyncState; int bytesRead = base.EndRead (cbs.result); if (target == Target.Normal) bf.Encipher(cbs.buffer, bytesRead); else bf.Decipher(cbs.buffer, bytesRead); return bytesRead; } /// <summary> /// The Read has completed. /// </summary> /// <param name="result">The result of the async write.</param> private void ReadComplete(IAsyncResult result) { CBState cbs = (CBState)result.AsyncState; cbs.callback(cbs); } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (target == Target.Normal) bf.Decipher(buffer, count); else bf.Encipher(buffer, count); return base.BeginWrite (buffer, offset, count, callback, state); } /// <summary> /// Move the current stream posistion to the specified location. /// </summary> /// <param name="offset">The offset from the origin to seek.</param> /// <param name="origin">The origin to seek from.</param> /// <returns>The new position.</returns> public override long Seek(long offset, SeekOrigin origin) { return stream.Seek(offset, origin); } /// <summary> /// Set the stream length. /// </summary> /// <param name="value">The length to set.</param> public override void SetLength(long value) { stream.SetLength(value); } } }
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Framework.Cli")] // Internal functions used by Framework.Cli assembly. namespace Framework { using Database.dbo; using Framework.App; using Framework.Doc; using Framework.Json; using Framework.Server; using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Web; public static class UtilFramework { /// <summary> /// Gets Version. This is the framework version. /// </summary> public static string Version { get { // dotnet --version // 6.0.101 // node --version // v16.13.1 // npm --version // 8.1.2 // npm run ng -- --version (run inside folder Application.Website/) // Angular CLI: 13.1.2 // Semantic versioning. v3.(Changes that break backward compatibility).(Backward compatible new features)(Backward compatible bug fixes) See also: https://docs.npmjs.com/about-semantic-versioning return "v3.52.21"; } } /// <summary> /// Gets time and pc name of Ci build. Value is set during build process. /// </summary> internal static string VersionBuild { get { // See also: method UtilCli.VersionBuild(); // Version tag with commit sha, build pc and time stamp. return "Build (local)"; /* VersionBuild */ } } /// <summary> /// Convert markdown text to html. /// </summary> public static string TextMdToHtml(string textMd, CssFrameworkEnum cssFrameworkEnum = CssFrameworkEnum.Bootstrap) { var appDoc = new AppDoc(); new MdPage(appDoc.MdDoc, textMd); appDoc.Parse(); var textHtml = appDoc.HtmlDoc.Render(); if (cssFrameworkEnum == CssFrameworkEnum.Bulma) { // See also: https://bulma.io/documentation/elements/image/#arbitrary-ratios-with-any-element textHtml = textHtml?.Replace("<iframe ", "<figure class=\"image is-16by9\"><iframe class=\"has-ratio\" width=\"640\" height=\"360\""); textHtml = textHtml?.Replace("</iframe>", "frameborder=\"0\" allowfullscreen </iframe></figure>"); } // Debug // UtilDoc.TextDebugWriteToFile(appDoc); return textHtml; } /// <summary> /// Gets ClientIpAddress. This is the web browser ip address. /// </summary> public static string ClientIpAddress { get { return UtilServer.Context.Connection.RemoteIpAddress.ToString(); } } /// <summary> /// Gets BackgroundServiceTimeHeartbeat. This is the last heartbeat of the background service. /// </summary> public static string BackgroundServiceTimeHeartbeat { get { return UtilServer.ServiceGet <BackgroundFrameworkService>().TimeHeartbeat; } } /// <summary> /// Gets ClientUserAgent. This is the web browser user agent. /// </summary> public static string ClientUserAgent { get { return UtilServer.Context.Request.Headers["User-Agent"].ToString(); } } /// <summary> /// Gets FileNameLog. This is the log file "log.csv". /// </summary> public static string FileNameLog { get { return UtilServer.FolderNameContentRoot() + "log.csv"; } } /// <summary> /// Returns root folder name. Does not throw an exception, if running on IIS server. /// </summary> internal static string FolderNameGet() { Uri result = new Uri(typeof(UtilFramework).Assembly.Location); result = new Uri(result, "../../../../"); return result.AbsolutePath; } /// <summary> /// Gets FolderName. This is the root folder where file Application.sln is located. /// Throws exception if running on IIS server. See also method: UtilServer.FolderNameContentRoot(); /// </summary> internal static string FolderName { get { if (UtilServer.IsIssServer) { throw new Exception("Running on ISS server! Use method UtilServer.FolderNameContentRoot();"); // Diferent folder structure! Use method: UtilServer.FolderNameContentRoot(); } return FolderNameGet(); } } /// <summary> /// Combines FolderName and path. /// Returns for example "Framework/Application.Website/Website01/". To be used for relative paths only. To build absolut path /// combine with property UtilFramework.FolderName or method UtilServer.FolderNameContentRoot(); /// </summary> /// <param name="folderName">For example "Default/"</param> /// <param name="path">For example "/index.html"</param> /// <returns>Returns for example "Default/index.html"</returns> internal static string FolderNameParse(string folderName, string path) { path = HttpUtility.UrlDecode(path); // For example "Hello%20World.pdf" string result = FolderNameParse(folderName); path = UtilFramework.StringEmpty(path); if (path.StartsWith("/") || path.StartsWith("\"")) { path = path.Substring(1); } result += path; return result; } /// <summary> /// Returns for example "Application.Website/Website01/". To be used for relative paths only. To build absolut path /// combine with property UtilFramework.FolderName or method UtilServer.FolderNameContentRoot(); /// </summary> internal static string FolderNameParse(string folderName) { if (UtilFramework.StringNull(folderName) == null) { return null; } folderName = UtilFramework.StringEmpty(folderName); folderName = folderName.Replace(@"\", "/"); if (folderName.StartsWith("/")) { folderName = folderName.Substring(1); } if (!folderName.EndsWith("/")) { folderName += "/"; } return folderName; } internal static void Assert(bool isAssert, string exceptionText) { if (!isAssert) { throw new Exception(exceptionText); } } internal static void Assert(bool isAssert) { if (!isAssert) { throw new Exception("Assert!"); } } internal static string ExceptionToString(Exception exception) { string result = null; while (exception != null) { if (result != null) { result += "; "; } result += exception.Message; exception = exception.InnerException; } return result; } /// <summary> /// Returns underlying tpye, if any. For example "type = typeof(int?)" returns "typeof(int)". /// </summary> internal static Type TypeUnderlying(Type type) { Type result = type; Type typeUnderlying = Nullable.GetUnderlyingType(type); if (typeUnderlying != null) { result = typeUnderlying; } return result; } internal static T ConfigFromJson<T>(string json) { object result; if (json == null) { result = JsonSerializer.Deserialize<T>("{}"); } else { result = JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions { AllowTrailingCommas = true }); } return (T)result; } internal static string ConfigToJson(object config, bool isIndented) { string json = JsonSerializer.Serialize(config, config.GetType(), new JsonSerializerOptions { WriteIndented = isIndented }); return json; } internal static T ConfigLoad<T>(string fileName) { string json = UtilFramework.FileLoad(fileName); object result = ConfigFromJson<T>(json); return (T)result; } /// <summary> /// Write (*.json) file, if modified. /// </summary> internal static void ConfigSave(object config, string fileName) { string json = ConfigToJson(config, isIndented: true); bool isModified = true; if (File.Exists(fileName)) { string jsonOld = File.ReadAllText(fileName); if (jsonOld == json) { isModified = false; } } if (isModified) { File.WriteAllText(fileName, json); Console.WriteLine(string.Format("Config saved to ({0})", fileName)); } } /// <summary> /// Returns null if value is empty string. Use for incoming and outgoing interfaces. /// </summary> internal static T StringNull<T>(T value) { T result = value; if (typeof(T) == typeof(string)) { if (((string)(object)value) == "") { result = (T)(object)null; } } return result; } /// <summary> /// Returns empty if value is null string. Use to get string length. /// </summary> internal static T StringEmpty<T>(T value) { T result = value; if (typeof(T) == typeof(string)) { if (((string)(object)value) == null) { result = (T)(object)""; } } return result; } internal static bool IsSubclassOf(Type type, Type typeBase) { if (type == null) { return false; } if (typeBase.IsGenericType == false) { return type.IsSubclassOf(typeBase) || type == typeBase; } else { while (type != null && type != typeof(object)) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeBase) { return true; } type = type.BaseType; } } return false; } /// <summary> /// Returns true for example for type "int?" /// </summary> internal static bool IsNullable(Type type) { if (type == typeof(string)) { return true; } if (type == typeof(byte[])) { return true; } return Nullable.GetUnderlyingType(type) != null; } internal static string Replace(string text, string find, string replace) { UtilFramework.Assert(text.Contains(find)); string result = text.Replace(find, replace); return result; } /// <summary> /// Search 'find' in every line. If found replace line with 'replace'. /// </summary> /// <param name="text">Text file.</param> /// <param name="find">Text to find in line.</param> /// <param name="replace">Text to replace line with.</param> /// <returns>Returns modified text file.</returns> internal static string ReplaceLine(string text, string find, string replace) { bool isFind = false; StringBuilder result = new StringBuilder(); using (var reader = new StringReader(text)) { string line; while ((line = reader.ReadLine()) != null) { if (line.Contains(find)) { isFind = true; line = replace; } result.AppendLine(line); } } UtilFramework.Assert(isFind, string.Format("Text not found! ({0})", find)); return result.ToString(); } /// <summary> /// Returns count of how many time 'find' has been found in 'text'. /// </summary> internal static int FindCount(string text, string find) { int result = 0; int index = 0; do { index = text.IndexOf(find, index); if (index != -1) { result += 1; index += find.Length; } } while (index != -1); return result; } /// <summary> /// Used for cli and stopwatch. Resolution seconds or milliseconds. See also method DateTimeToText(); /// </summary> internal static string DateTimeToString(DateTime dateTime, bool isThousand = false) { string format = "yyyy-MM-dd HH:mm:ss"; if (isThousand) { format += ".fff"; } return dateTime.ToString(format); } /// <summary> /// See log in Visual Studio Output window. /// </summary> internal static void LogDebug(string text) { UtilStopwatch.Log(string.Format("{0} {1}", UtilFramework.DateTimeToString(DateTime.Now, true), text)); } /// <summary> /// Returns newly created instance of type with parameterless constructor. /// </summary> /// <param name="type">Type with parameterless constructor.</param> /// <returns>Returns instance of type.</returns> internal static object TypeToObject(Type type) { return Activator.CreateInstance(type); } internal static string FileLoad(string fileName) { return File.ReadAllText(fileName); } internal static void FileSave(string fileName, string text) { lock (typeof(object)) { File.WriteAllText(fileName, text); } } internal static List<string> FileNameList(string folderName, string searchPattern) { return Directory.GetFiles(folderName, searchPattern, SearchOption.AllDirectories).ToList(); } internal static List<string> FileNameList(string folderName) { return FileNameList(folderName, "*.*"); } private static readonly ConcurrentDictionary<Type, string> typeToNameListCache = new ConcurrentDictionary<Type, string>(); /// <summary> /// Returns for example: "Database.dbo.FrameworkScript" /// </summary> /// <param name="isIncludeAssemblyName">If true, function returns for example: "Database.dbo.FrameworkScript, Framework". Use this option if used in connection with <see cref="TypeFromName(string)"/></param> internal static string TypeToName(Type type, bool isIncludeAssemblyName = false) { if (isIncludeAssemblyName == false) { return type.FullName; } else { string result = typeToNameListCache.GetOrAdd(type, (Type type) => { return type.FullName + ", " + type.Assembly.GetName().Name; // Slow }); return result; } } /// <summary> /// (TypeName, Type). Cache. /// </summary> private static readonly ConcurrentDictionary<string, Type> typeFromNameListCache = new ConcurrentDictionary<string, Type>(); /// <summary> /// Returns type of for example Application.AppMain" or better "Application.AppMain, Application". /// </summary> internal static Type TypeFromName(string typeName) { if (!typeFromNameListCache.ContainsKey(typeName)) { Type type = Type.GetType(typeName); typeFromNameListCache.TryAdd(typeName, type); } Type result = typeFromNameListCache[typeName]; UtilFramework.Assert(result != null, "TypeName unknown!"); return result; } internal static List<List<T>> Split<T>(List<T> list, int countMax) { List<List<T>> result = new List<List<T>>(); for (int i = 0; i < list.Count; i++) { if (i % countMax == 0) { result.Add(new List<T>()); } result[^1].Add(list[i]); } return result; } /// <summary> /// Used for row data. /// </summary> internal static DateTime? DateTimeFromText(string text, bool isTime = true) { DateTime? result = null; if (text != null) { if (isTime) { if (!text.Contains(":")) { isTime = false; } } if (text.Contains("-")) { if (isTime == false) { result = DateTime.ParseExact(text, "yyyy-M-d", CultureInfo.InvariantCulture); // Parse for example: "2000-01-31". } else { result = DateTime.ParseExact(text, "yyyy-M-d hh:mm", CultureInfo.InvariantCulture); // Parse for example: "2000-01-31 13:15". } } else { if (text.Contains(".")) { if (isTime == false) { result = DateTime.ParseExact(text, "d.M.yyyy", CultureInfo.InvariantCulture); // Parse for example: "31.1.2000". } else { result = DateTime.ParseExact(text, "d.M.yyyy hh:mm", CultureInfo.InvariantCulture); // Parse for example: "31.1.2000 13:15". } } else { if (isTime == false) { result = DateTime.ParseExact(text, "M/d/yyyy", CultureInfo.InvariantCulture); // Parse for example: "1/31/2000". } else { result = DateTime.ParseExact(text, "M/d/yyyy hh:mm", CultureInfo.InvariantCulture); // Parse for example: "1/31/2000 13:15". } } } } return result; } /// <summary> /// Used for row data. Resolution minutes. /// </summary> internal static string DateTimeToText(DateTime? value, bool isTime = true) { string result = null; if (value != null) { if (isTime == false) { result = ((DateTime)value).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } else { result = ((DateTime)value).ToString("yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture); } } return result; } /// <summary> /// Returns value as text with thousands separator. /// </summary> internal static string IntToText(int value) { return string.Format("{0:N0}", value); } /// <summary> /// Returns list of text chunks with max length of 80. /// </summary> internal static List<string> SplitChunk(string text, int lengthChunkMax = 80) { List<string> result = new List<string>(); int index = 0; do { int length = Math.Min(lengthChunkMax, text.Length - index); string textChunk = text.Substring(index, length); index += length; result.Add(textChunk); } while (index != text.Length); return result; } /// <summary> /// Gets FrameworkAssembly. See also class AppCli. There is AssemblyFramework, AssemblyFrameworkCli, AssemblyApplication, AssemblyApplicationCli and AssemblyApplicationDatabase. /// </summary> internal static Assembly AssemblyFramework { get { return typeof(FrameworkDeployDb).Assembly; } } /// <summary> /// Returns for example: ".jpg". /// </summary> internal static string FileNameExtension(string fileName) { var result = StringNull(Path.GetExtension(fileName)); return result; } /// <summary> /// Close all running node.exe /// </summary> internal static void NodeClose() { // Log ILogger logger = null; if (UtilServer.ServiceProvider != null) { var loggerFactory = UtilServer.ServiceGet<ILoggerFactory>(); logger = loggerFactory.CreateLogger(typeof(UtilFramework)); } // Close node.exe foreach (var process in Process.GetProcesses().Where(item => item.MainWindowTitle.EndsWith("node.exe"))) { var logText = $"Close node.exe ({ process.Id })"; if (logger != null) { logger.LogInformation(logText); } else { Console.WriteLine(logText); } process.Kill(); } } /// <summary> /// Split text in camel case blocks. /// </summary> internal class CamelCase { public CamelCase(string text) { this.Text = text; this.TextList = new List<string>(); // Index List<int> indexList = new List<int>(); bool? isUpper = null; for (int index = 0; index < Text.Length; index++) { Char c = Text[index]; if ((Char.IsUpper(c) && isUpper == false) || isUpper == null) { indexList.Add(index); } else { indexList[^1] = indexList[^1] + 1; } isUpper = Char.IsUpper(c); } // Split int indexPrevious = 0; foreach (var index in indexList) { TextList.Add(Text.Substring(indexPrevious, index - indexPrevious + 1)); indexPrevious = index + 1; } } public bool StartsWith(CamelCase value) { bool result = true; for (int i = 0; i < value.TextList.Count; i++) { if (TextList.Count - 1 >= i) { if (value.TextList[i] != TextList[i]) { result = false; break; } } else { result = false; break; } } return result; } public bool StartsWith(string value) { return StartsWith(new CamelCase(value)); } public bool EndsWith(CamelCase value) { bool result = true; int indexValue = value.TextList.Count - 1; int index = TextList.Count - 1; for (int i = indexValue; i >= 0; i--) { if (index >= 0 && indexValue >= 0) { if (value.TextList[indexValue] != TextList[index]) { result = false; break; } } else { result = false; break; } indexValue--; index--; } return result; } public bool EndsWith(string value) { return EndsWith(new CamelCase(value)); } public readonly string Text; public readonly List<string> TextList; } /// <summary> /// Returns hash and salt of password. /// </summary> /// <param name="password">User password</param> /// <param name="passwordHash">Returns password hash as 128 text hex characters.</param> /// <param name="passwordSalt">Returns password salt as 128 text hex characters.</param> /// <param name="passwordSaltConfig">Application configuration salt as 128 text hex characters.</param> /// <param name="count">Number of calculation (time).</param> private static void PasswordHash(string password, out string passwordHash, out string passwordSalt, string passwordSaltConfig = null, int count = 100000) { // Salt var saltArray = new byte[64]; using (var random = RandomNumberGenerator.Create()) { random.GetBytes(saltArray); } passwordSalt = BitConverter.ToString(saltArray).Replace("-", ""); // Password password = BitConverter.ToString(Encoding.Unicode.GetBytes(password)).Replace("-", ""); // Password + Salt var saltAndPasswordText = passwordSalt + password + passwordSaltConfig; // Hash passwordHash = null; using (var sha = SHA512.Create()) { for (int i = 0; i < count; i++) { passwordHash = BitConverter.ToString(sha.ComputeHash(Encoding.Unicode.GetBytes(saltAndPasswordText))).Replace("-", ""); saltAndPasswordText = passwordSalt + passwordHash; } } } /// <summary> /// Returns hash and salt of password. /// </summary> /// <param name="password">User password</param> /// <param name="passwordHash">Returns password hash as 128 text hex characters.</param> /// <param name="passwordSalt">Returns password salt as 128 text hex characters.</param> public static void PasswordHash(string password, out string passwordHash, out string passwordSalt) { string passwordSaltConfig = new AppSelector().ConfigDomain.PasswordSalt; PasswordHash(password, out passwordHash, out passwordSalt, passwordSaltConfig); } /// <summary> /// Returns true, if password is correct. /// </summary> /// <param name="password">User entered password.</param> /// <param name="passwordHash">Password hash as 128 text hex characters.</param> /// <param name="passwordSalt">Password salt as 128 text hex characters.</param> /// <param name="passwordSaltConfig">Application configuration salt as 128 text hex characters.</param> /// <param name="count">Number of calculation (time).</param> private static bool PasswordIsValid(string password, string passwordHash, string passwordSalt, string passwordSaltConfig = null, int count = 100000) { // Password password = BitConverter.ToString(Encoding.Unicode.GetBytes(password == null ? "" : password)).Replace("-", ""); // Password + Salt var saltAndPasswordText = passwordSalt + password + passwordSaltConfig; // Hash string hashNew = null; using (var sha = SHA512.Create()) { for (int i = 0; i < count; i++) { hashNew = BitConverter.ToString(sha.ComputeHash(Encoding.Unicode.GetBytes(saltAndPasswordText))).Replace("-", ""); saltAndPasswordText = passwordSalt + hashNew; } } return passwordHash == hashNew; } /// <summary> /// Returns true, if password is correct. /// </summary> /// <param name="password">User entered password.</param> /// <param name="passwordHash">Password hash as 128 text hex characters.</param> /// <param name="passwordSalt">Password salt as 128 text hex characters.</param> public static bool PasswordIsValid(string password, string passwordHash, string passwordSalt) { string passwordSaltConfig = new AppSelector().ConfigDomain.PasswordSalt; return PasswordIsValid(password, passwordHash, passwordSalt, passwordSaltConfig); } /// <summary> /// Returns a salt as 128 text hex characters for the application config file. /// </summary> public static string PasswordSaltConfigCreate() { var saltArray = new byte[64]; using (var random = RandomNumberGenerator.Create()) { random.GetBytes(saltArray); } return BitConverter.ToString(saltArray).Replace("-", ""); } /// <summary> /// Translate text into a different language. /// </summary> /// <param name="appJson">Application for which this text is for. (See also feature ExternalGit).</param> /// <param name="itemName">Dictionary key for text.</param> /// <param name="text">Default text.</param> /// <param name="languageName">Language to translate to. See also sql table FrameworkLanguage.</param> /// <returns>Returns into languageId translated text. If no translation entry is found text is returned.</returns> internal static string Language(AppJson appJson, string itemName, string text, string languageName) { var result = text; if (languageName != null) { var service = UtilServer.ServiceGet<BackgroundFrameworkService>(); result = service.Language(appJson.GetType().FullName, languageName, itemName, text); } return result; } /// <summary> /// Translate text into a different language. Data grid related translation. /// </summary> /// <param name="grid">Translation for this data grid.</param> /// <param name="itemName">Dictionary key for text.</param> /// <param name="text">Default text.</param> /// <returns>Returns translated text. If no translation entry is found text is returned.</returns> private static string LanguageGrid(Grid grid, string itemName, string text) { var result = text; if (grid.TypeRow.Assembly != typeof(UtilFramework).Assembly) // Do not translate Framework data grid. { var appJson = grid.ComponentOwner<AppJson>(); var settingResult = appJson.SettingInternal(grid); // Get GridLanguageName. result = Language(appJson, grid.TypeRow.FullName + "." + itemName, text, settingResult.GridLanguageName); } return result; } /// <summary> /// Translate data grid cell text into a different language. /// </summary> /// <param name="grid">Translation for this data grid.</param> /// <param name="fieldNameCSharp">Translation for this column.</param> /// <param name="text">Default text.</param> /// <returns></returns> internal static string LanguageGridCellText(Grid grid, string fieldNameCSharp, string text) { return LanguageGrid(grid, fieldNameCSharp + ".CellText(" + text + ")", text); } /// <summary> /// Translate data grid column text into a different language. /// </summary> /// <param name="grid">Translation for this data grid.</param> /// <param name="fieldNameCSharp">Translation for this column.</param> /// <param name="text">Default text.</param> /// <returns>Returns translated text. If no translation entry is found text is returned.</returns> internal static string LanguageGridColumnText(Grid grid, string fieldNameCSharp, string text) { return LanguageGrid(grid, fieldNameCSharp + ".ColumnText()", text); } /// <summary> /// See also cli command externalGit method ExecuteCopy(); /// </summary> [AttributeUsage(AttributeTargets.Class)] public class ExternalGitAttribute : Attribute { } } }
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using System.IO.IsolatedStorage; using System.Windows.Resources; using System.Windows.Interop; using System.Runtime.Serialization.Json; using System.IO; using System.ComponentModel; using System.Xml.Linq; using WPCordovaClassLib.Cordova.Commands; using System.Diagnostics; using System.Text; using WPCordovaClassLib.Cordova; using System.Threading; using Microsoft.Phone.Shell; using WPCordovaClassLib.Cordova.JSON; using WPCordovaClassLib.CordovaLib; namespace WPCordovaClassLib { public partial class CordovaView : UserControl { /// <summary> /// Indicates whether web control has been loaded and no additional initialization is needed. /// Prevents data clearing during page transitions. /// </summary> private bool IsBrowserInitialized = false; /// <summary> /// Set when the user attaches a back button handler inside the WebBrowser /// </summary> private bool OverrideBackButton = false; /// <summary> /// Sentinal to keep track of page changes as a result of the hardware back button /// Set to false when the back-button is pressed, which calls js window.history.back() /// If the page changes as a result of the back button the event is cancelled. /// </summary> private bool PageDidChange = false; private static string AppRoot = ""; /// <summary> /// Handles native api calls /// </summary> private NativeExecution nativeExecution; protected BrowserMouseHelper bmHelper; private ConfigHandler configHandler; private Dictionary<string, IBrowserDecorator> browserDecorators; public System.Windows.Controls.Grid _LayoutRoot { get { return ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); } } public WebBrowser Browser { get { return CordovaBrowser; } } /* * Setting StartPageUri only has an effect if called before the view is loaded. **/ protected Uri _startPageUri = null; public Uri StartPageUri { get { if (_startPageUri == null) { // default return new Uri(AppRoot + "www/index.html", UriKind.Relative); } else { return _startPageUri; } } set { if (!this.IsBrowserInitialized) { _startPageUri = value; } } } /// <summary> /// Gets or sets whether to suppress bouncy scrolling of /// the WebBrowser control; /// </summary> public bool DisableBouncyScrolling { get; set; } public CordovaView() { InitializeComponent(); if (DesignerProperties.IsInDesignTool) { return; } StartupMode mode = PhoneApplicationService.Current.StartupMode; if (mode == StartupMode.Launch) { PhoneApplicationService service = PhoneApplicationService.Current; service.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated); service.Launching += new EventHandler<LaunchingEventArgs>(AppLaunching); service.Deactivated += new EventHandler<DeactivatedEventArgs>(AppDeactivated); service.Closing += new EventHandler<ClosingEventArgs>(AppClosing); } else { } // initializes native execution logic configHandler = new ConfigHandler(); configHandler.LoadAppPackageConfig(); if (configHandler.ContentSrc != null) { if (Uri.IsWellFormedUriString(configHandler.ContentSrc, UriKind.Absolute)) { this.StartPageUri = new Uri(configHandler.ContentSrc, UriKind.Absolute); } else { this.StartPageUri = new Uri(AppRoot + "www/" + configHandler.ContentSrc, UriKind.Relative); } } browserDecorators = new Dictionary<string, IBrowserDecorator>(); nativeExecution = new NativeExecution(ref this.CordovaBrowser); bmHelper = new BrowserMouseHelper(ref this.CordovaBrowser); CreateDecorators(); } /* * browserDecorators are a collection of plugin-like classes (IBrowserDecorator) that add some bit of functionality to the browser. * These are somewhat different than plugins in that they are usually not async and patch a browser feature that we would * already expect to have. Essentially these are browser polyfills that are patched from the outside in. * */ void CreateDecorators() { XHRHelper xhrProxy = new XHRHelper(); xhrProxy.Browser = CordovaBrowser; browserDecorators.Add("XHRLOCAL", xhrProxy); OrientationHelper orientHelper = new OrientationHelper(); orientHelper.Browser = CordovaBrowser; browserDecorators.Add("Orientation", orientHelper); ConsoleHelper console = new ConsoleHelper(); console.Browser = CordovaBrowser; browserDecorators.Add("ConsoleLog", console); } void AppClosing(object sender, ClosingEventArgs e) { Debug.WriteLine("AppClosing"); } void AppDeactivated(object sender, DeactivatedEventArgs e) { Debug.WriteLine("INFO: AppDeactivated"); try { CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('pause');" }); } catch (Exception) { Debug.WriteLine("ERROR: Pause event error"); } } void AppLaunching(object sender, LaunchingEventArgs e) { Debug.WriteLine("INFO: AppLaunching"); } void AppActivated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e) { Debug.WriteLine("INFO: AppActivated"); try { CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('resume');" }); } catch (Exception) { Debug.WriteLine("ERROR: Resume event error"); } } void CordovaBrowser_Loaded(object sender, RoutedEventArgs e) { this.bmHelper.ScrollDisabled = this.DisableBouncyScrolling; if (DesignerProperties.IsInDesignTool) { return; } // prevents refreshing web control to initial state during pages transitions if (this.IsBrowserInitialized) return; try { // Before we possibly clean the ISO-Store, we need to grab our generated UUID, so we can rewrite it after. string deviceUUID = ""; using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) { try { IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage); using (StreamReader reader = new StreamReader(fileStream)) { deviceUUID = reader.ReadLine(); } } catch (Exception /*ex*/) { deviceUUID = Guid.NewGuid().ToString(); Debug.WriteLine("Updating IsolatedStorage for APP:DeviceID :: " + deviceUUID); IsolatedStorageFileStream file = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Create, FileAccess.Write, appStorage); using (StreamWriter writeFile = new StreamWriter(file)) { writeFile.WriteLine(deviceUUID); writeFile.Close(); } } } /* * 11/08/12 Ruslan Kokorev * Copying files to isolated storage is no more required in WP8. WebBrowser control now works with files located in XAP. */ //StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("CordovaSourceDictionary.xml", UriKind.Relative)); //if (streamInfo != null) //{ // StreamReader sr = new StreamReader(streamInfo.Stream); // //This will Read Keys Collection for the xml file // XDocument document = XDocument.Parse(sr.ReadToEnd()); // var files = from results in document.Descendants("FilePath") // select new // { // path = (string)results.Attribute("Value") // }; // StreamResourceInfo fileResourceStreamInfo; // using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) // { // foreach (var file in files) // { // fileResourceStreamInfo = Application.GetResourceStream(new Uri(file.path, UriKind.Relative)); // if (fileResourceStreamInfo != null) // { // using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream)) // { // byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length); // string strBaseDir = AppRoot + file.path.Substring(0, file.path.LastIndexOf(System.IO.Path.DirectorySeparatorChar)); // if (!appStorage.DirectoryExists(strBaseDir)) // { // Debug.WriteLine("INFO: Creating Directory :: " + strBaseDir); // appStorage.CreateDirectory(strBaseDir); // } // // This will truncate/overwrite an existing file, or // using (IsolatedStorageFileStream outFile = appStorage.OpenFile(AppRoot + file.path, FileMode.Create)) // { // Debug.WriteLine("INFO: Writing data for " + AppRoot + file.path + " and length = " + data.Length); // using (var writer = new BinaryWriter(outFile)) // { // writer.Write(data); // } // } // } // } // else // { // Debug.WriteLine("ERROR: Failed to write file :: " + file.path + " did you forget to add it to the project?"); // } // } // } //} CordovaBrowser.Navigate(StartPageUri); IsBrowserInitialized = true; AttachHardwareButtonHandlers(); } catch (Exception ex) { Debug.WriteLine("ERROR: Exception in CordovaBrowser_Loaded :: {0}", ex.Message); } } void AttachHardwareButtonHandlers() { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { page.BackKeyPress += new EventHandler<CancelEventArgs>(page_BackKeyPress); // CB-2347 -jm string fullscreen = configHandler.GetPreference("fullscreen"); bool bFullScreen = false; if (bool.TryParse(fullscreen, out bFullScreen) && bFullScreen) { SystemTray.SetIsVisible(page, false); } } } } void page_BackKeyPress(object sender, CancelEventArgs e) { if (OverrideBackButton) { try { CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('backbutton', {}, true);" }); e.Cancel = true; } catch (Exception ex) { Console.WriteLine("Exception while invoking backbutton into cordova view: " + ex.Message); } } else { try { PageDidChange = false; Uri uriBefore = this.Browser.Source; // calling js history.back with result in a page change if history was valid. CordovaBrowser.InvokeScript("eval", new string[] { "(function(){window.history.back();})()" }); Uri uriAfter = this.Browser.Source; // drake: always exit when back button is preseed (to pass windows 8 phone certification) //e.Cancel = PageDidChange || (uriBefore != uriAfter); e.Cancel = false; } catch (Exception) { e.Cancel = false; // exit the app ... ? } } } void CordovaBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e) { Debug.WriteLine("CordovaBrowser_LoadCompleted"); string[] autoloadPlugs = this.configHandler.AutoloadPlugins; foreach (string plugName in autoloadPlugs) { //nativeExecution.ProcessCommand(commandCallParams); } string nativeReady = "(function(){ cordova.require('cordova/channel').onNativeReady.fire()})();"; try { CordovaBrowser.InvokeScript("execScript", new string[] { nativeReady }); } catch (Exception /*ex*/) { Debug.WriteLine("Error calling js to fire nativeReady event. Did you include cordova.js in your html script tag?"); } if (this.CordovaBrowser.Opacity < 1) { FadeIn.Begin(); } } void CordovaBrowser_Navigating(object sender, NavigatingEventArgs e) { if (!configHandler.URLIsAllowed(e.Uri.ToString())) { Debug.WriteLine("Whitelist exception: Stopping browser from navigating to :: " + e.Uri.ToString()); e.Cancel = true; return; } this.PageDidChange = true; this.nativeExecution.ResetAllCommands(); } /* * This method does the work of routing commands * NotifyEventArgs.Value contains a string passed from JS * If the command already exists in our map, we will just attempt to call the method(action) specified, and pass the args along * Otherwise, we create a new instance of the command, add it to the map, and call it ... * This method may also receive JS error messages caught by window.onerror, in any case where the commandStr does not appear to be a valid command * it is simply output to the debugger output, and the method returns. * **/ void CordovaBrowser_ScriptNotify(object sender, NotifyEventArgs e) { string commandStr = e.Value; string commandName = commandStr.Split('/').FirstOrDefault(); if (browserDecorators.ContainsKey(commandName)) { browserDecorators[commandName].HandleCommand(commandStr); return; } CordovaCommandCall commandCallParams = CordovaCommandCall.Parse(commandStr); if (commandCallParams == null) { // ERROR Debug.WriteLine("ScriptNotify :: " + commandStr); } else if (commandCallParams.Service == "CoreEvents") { switch (commandCallParams.Action.ToLower()) { case "overridebackbutton": string arg0 = JsonHelper.Deserialize<string[]>(commandCallParams.Args)[0]; this.OverrideBackButton = (arg0 != null && arg0.Length > 0 && arg0.ToLower() == "true"); break; } } else { if (configHandler.IsPluginAllowed(commandCallParams.Service)) { nativeExecution.ProcessCommand(commandCallParams); } else { Debug.WriteLine("Error::Plugin not allowed in config.xml. " + commandCallParams.Service); } } } public void LoadPage(string url) { if (this.configHandler.URLIsAllowed(url)) { this.CordovaBrowser.Navigate(new Uri(url, UriKind.RelativeOrAbsolute)); } else { Debug.WriteLine("Oops, Can't load url based on config.xml :: " + url); } } private void CordovaBrowser_Unloaded(object sender, RoutedEventArgs e) { } private void CordovaBrowser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e) { Debug.WriteLine("CordovaBrowser_NavigationFailed :: " + e.Uri.ToString()); } private void CordovaBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { foreach(IBrowserDecorator iBD in browserDecorators.Values) { iBD.InjectScript(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using SimpleInjectorWithWebAPI.Areas.HelpPage.Models; namespace SimpleInjectorWithWebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL) #region License /* * ChunkStream.cs * * This code is derived from ChunkStream.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2003 Ximian, Inc (http://www.ximian.com) * Copyright (c) 2012-2015 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <[email protected]> */ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; namespace WebSocketSharp.Net { internal class ChunkStream { #region Private Fields private int _chunkRead; private int _chunkSize; private List<Chunk> _chunks; private bool _gotIt; private WebHeaderCollection _headers; private StringBuilder _saved; private bool _sawCr; private InputChunkState _state; private int _trailerState; #endregion #region Public Constructors public ChunkStream (WebHeaderCollection headers) { _headers = headers; _chunkSize = -1; _chunks = new List<Chunk> (); _saved = new StringBuilder (); } public ChunkStream (byte[] buffer, int offset, int count, WebHeaderCollection headers) : this (headers) { Write (buffer, offset, count); } #endregion #region Internal Properties internal WebHeaderCollection Headers { get { return _headers; } } #endregion #region Public Properties public int ChunkLeft { get { return _chunkSize - _chunkRead; } } public bool WantMore { get { return _state != InputChunkState.End; } } #endregion #region Private Methods private int read (byte[] buffer, int offset, int count) { var nread = 0; var cnt = _chunks.Count; for (var i = 0; i < cnt; i++) { var chunk = _chunks[i]; if (chunk == null) continue; if (chunk.ReadLeft == 0) { _chunks[i] = null; continue; } nread += chunk.Read (buffer, offset + nread, count - nread); if (nread == count) break; } return nread; } private static string removeChunkExtension (string value) { var idx = value.IndexOf (';'); return idx > -1 ? value.Substring (0, idx) : value; } private InputChunkState seekCrLf (byte[] buffer, ref int offset, int length) { if (!_sawCr) { if (buffer[offset++] != 13) throwProtocolViolation ("CR is expected."); _sawCr = true; if (offset == length) return InputChunkState.DataEnded; } if (buffer[offset++] != 10) throwProtocolViolation ("LF is expected."); return InputChunkState.None; } private InputChunkState setChunkSize (byte[] buffer, ref int offset, int length) { byte b = 0; while (offset < length) { b = buffer[offset++]; if (_sawCr) { if (b != 10) throwProtocolViolation ("LF is expected."); break; } if (b == 13) { _sawCr = true; continue; } if (b == 10) throwProtocolViolation ("LF is unexpected."); if (b == 32) // SP _gotIt = true; if (!_gotIt) _saved.Append ((char) b); if (_saved.Length > 20) throwProtocolViolation ("The chunk size is too long."); } if (!_sawCr || b != 10) return InputChunkState.None; _chunkRead = 0; try { _chunkSize = Int32.Parse ( removeChunkExtension (_saved.ToString ()), NumberStyles.HexNumber); } catch { throwProtocolViolation ("The chunk size cannot be parsed."); } if (_chunkSize == 0) { _trailerState = 2; return InputChunkState.Trailer; } return InputChunkState.Data; } private InputChunkState setTrailer (byte[] buffer, ref int offset, int length) { // Check if no trailer. if (_trailerState == 2 && buffer[offset] == 13 && _saved.Length == 0) { offset++; if (offset < length && buffer[offset] == 10) { offset++; return InputChunkState.End; } offset--; } while (offset < length && _trailerState < 4) { var b = buffer[offset++]; _saved.Append ((char) b); if (_saved.Length > 4196) throwProtocolViolation ("The trailer is too long."); if (_trailerState == 1 || _trailerState == 3) { if (b != 10) throwProtocolViolation ("LF is expected."); _trailerState++; continue; } if (b == 13) { _trailerState++; continue; } if (b == 10) throwProtocolViolation ("LF is unexpected."); _trailerState = 0; } if (_trailerState < 4) return InputChunkState.Trailer; _saved.Length -= 2; var reader = new StringReader (_saved.ToString ()); string line; while ((line = reader.ReadLine ()) != null && line.Length > 0) _headers.Add (line); return InputChunkState.End; } private static void throwProtocolViolation (string message) { throw new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null); } private void write (byte[] buffer, ref int offset, int length) { if (_state == InputChunkState.End) throwProtocolViolation ("The chunks were ended."); if (_state == InputChunkState.None) { _state = setChunkSize (buffer, ref offset, length); if (_state == InputChunkState.None) return; _saved.Length = 0; _sawCr = false; _gotIt = false; } if (_state == InputChunkState.Data && offset < length) { _state = writeData (buffer, ref offset, length); if (_state == InputChunkState.Data) return; } if (_state == InputChunkState.DataEnded && offset < length) { _state = seekCrLf (buffer, ref offset, length); if (_state == InputChunkState.DataEnded) return; _sawCr = false; } if (_state == InputChunkState.Trailer && offset < length) { _state = setTrailer (buffer, ref offset, length); if (_state == InputChunkState.Trailer) return; _saved.Length = 0; } if (offset < length) write (buffer, ref offset, length); } private InputChunkState writeData (byte[] buffer, ref int offset, int length) { var cnt = length - offset; var left = _chunkSize - _chunkRead; if (cnt > left) cnt = left; var data = new byte[cnt]; Buffer.BlockCopy (buffer, offset, data, 0, cnt); _chunks.Add (new Chunk (data)); offset += cnt; _chunkRead += cnt; return _chunkRead == _chunkSize ? InputChunkState.DataEnded : InputChunkState.Data; } #endregion #region Internal Methods internal void ResetBuffer () { _chunkRead = 0; _chunkSize = -1; _chunks.Clear (); } internal int WriteAndReadBack (byte[] buffer, int offset, int writeCount, int readCount) { Write (buffer, offset, writeCount); return Read (buffer, offset, readCount); } #endregion #region Public Methods public int Read (byte[] buffer, int offset, int count) { if (count <= 0) return 0; return read (buffer, offset, count); } public void Write (byte[] buffer, int offset, int count) { if (count <= 0) return; write (buffer, ref offset, offset + count); } #endregion } } #endif
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public abstract class AbstractCodeMember : AbstractKeyedCodeElement { internal AbstractCodeMember( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal AbstractCodeMember( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } protected SyntaxNode GetContainingTypeNode() { return LookupNode().Ancestors().Where(CodeModelService.IsType).FirstOrDefault(); } public override object Parent { get { var containingTypeNode = GetContainingTypeNode(); if (containingTypeNode == null) { throw Exceptions.ThrowEUnexpected(); } return FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingTypeNode); } } public EnvDTE.vsCMAccess Access { get { var node = LookupNode(); return CodeModelService.GetAccess(node); } set { UpdateNode(FileCodeModel.UpdateAccess, value); } } public EnvDTE.CodeElements Attributes { get { return AttributeCollection.Create(this.State, this); } } public string Comment { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetComment(node); } set { UpdateNode(FileCodeModel.UpdateComment, value); } } public string DocComment { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetDocComment(node); } set { UpdateNode(FileCodeModel.UpdateDocComment, value); } } public bool IsGeneric { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetIsGeneric(node); } } public bool IsShared { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetIsShared(node, LookupSymbol()); } set { UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateIsShared, value); } } public bool MustImplement { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetMustImplement(node); } set { UpdateNode(FileCodeModel.UpdateMustImplement, value); } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetOverrideKind(node); } set { UpdateNode(FileCodeModel.UpdateOverrideKind, value); } } internal virtual ImmutableArray<SyntaxNode> GetParameters() { throw Exceptions.ThrowEFail(); } public EnvDTE.CodeElements Parameters { get { return ParameterCollection.Create(this.State, this); } } public EnvDTE.CodeParameter AddParameter(string name, object type, object position) { return FileCodeModel.EnsureEditor(() => { // The parameters are part of the node key, so we need to update it // after adding a parameter. var node = LookupNode(); var nodePath = new SyntaxPath(node); var parameter = FileCodeModel.AddParameter(this, node, name, type, position); ReacquireNodeKey(nodePath, CancellationToken.None); return parameter; }); } public void RemoveParameter(object element) { FileCodeModel.EnsureEditor(() => { // The parameters are part of the node key, so we need to update it // after removing a parameter. var node = LookupNode(); var nodePath = new SyntaxPath(node); var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Parameters.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.ElementIsNotValid, "element"); } codeElement.Delete(); ReacquireNodeKey(nodePath, CancellationToken.None); }); } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddAttribute(LookupNode(), name, value, position); }); } } }
using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using PetShop.Model; using System.Data; using PetShop.DBUtility; using PetShop.IProfileDAL; namespace PetShop.SQLProfileDAL { class PetShopProfileProvider : IPetShopProfileProvider { // Contst matching System.Web.Profile.ProfileAuthenticationOption.Anonymous private const int AUTH_ANONYMOUS = 0; // Contst matching System.Web.Profile.ProfileAuthenticationOption.Authenticated private const int AUTH_AUTHENTICATED = 1; // Contst matching System.Web.Profile.ProfileAuthenticationOption.All private const int AUTH_ALL = 2; /// <summary> /// Retrieve account information for current username and application. /// </summary> /// <param name="userName">User Name</param> /// <param name="appName">Application Name</param> /// <returns>Account information for current user</returns> public AddressInfo GetAccountInfo(string userName, string appName) { string sqlSelect = "SELECT Account.Email, Account.FirstName, Account.LastName, Account.Address1, Account.Address2, Account.City, Account.State, Account.Zip, Account.Country, Account.Phone FROM Account INNER JOIN Profiles ON Account.UniqueID = Profiles.UniqueID WHERE Profiles.Username = @Username AND Profiles.ApplicationName = @ApplicationName;"; SqlParameter[] parms = { new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256)}; parms[0].Value = userName; parms[1].Value = appName; AddressInfo addressInfo = null; SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlSelect, parms); while (dr.Read()) { string address2 = string.Empty; if (!dr.IsDBNull(4)) address2 = dr.GetString(4); addressInfo = new AddressInfo(dr.GetString(1), dr.GetString(2), dr.GetString(3), address2, dr.GetString(5), dr.GetString(6), dr.GetString(7), dr.GetString(8), dr.GetString(9), dr.GetString(0)); } dr.Close(); return addressInfo; } /// <summary> /// Update account for current user /// </summary> /// <param name="uniqueID">User id</param> /// <param name="addressInfo">Account information for current user</param> public void SetAccountInfo(int uniqueID, AddressInfo addressInfo) { string sqlDelete = "DELETE FROM Account WHERE UniqueID = @UniqueID;"; SqlParameter param = new SqlParameter("@UniqueID", SqlDbType.Int); param.Value = uniqueID; string sqlInsert = "INSERT INTO Account (UniqueID, Email, FirstName, LastName, Address1, Address2, City, State, Zip, Country, Phone) VALUES (@UniqueID, @Email, @FirstName, @LastName, @Address1, @Address2, @City, @State, @Zip, @Country, @Phone);"; SqlParameter[] parms = { new SqlParameter("@UniqueID", SqlDbType.Int), new SqlParameter("@Email", SqlDbType.VarChar, 80), new SqlParameter("@FirstName", SqlDbType.VarChar, 80), new SqlParameter("@LastName", SqlDbType.VarChar, 80), new SqlParameter("@Address1", SqlDbType.VarChar, 80), new SqlParameter("@Address2", SqlDbType.VarChar, 80), new SqlParameter("@City", SqlDbType.VarChar, 80), new SqlParameter("@State", SqlDbType.VarChar, 80), new SqlParameter("@Zip", SqlDbType.VarChar, 80), new SqlParameter("@Country", SqlDbType.VarChar, 80), new SqlParameter("@Phone", SqlDbType.VarChar, 80)}; parms[0].Value = uniqueID; parms[1].Value = addressInfo.Email; parms[2].Value = addressInfo.FirstName; parms[3].Value = addressInfo.LastName; parms[4].Value = addressInfo.Address1; parms[5].Value = addressInfo.Address2; parms[6].Value = addressInfo.City; parms[7].Value = addressInfo.State; parms[8].Value = addressInfo.Zip; parms[9].Value = addressInfo.Country; parms[10].Value = addressInfo.Phone; SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringProfile); conn.Open(); SqlTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted); try { SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sqlDelete, param); SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sqlInsert, parms); trans.Commit(); } catch(Exception e) { trans.Rollback(); throw new ApplicationException(e.Message); } finally { conn.Close(); } } /// <summary> /// Retrieve collection of shopping cart items /// </summary> /// <param name="userName">User Name</param> /// <param name="appName">Application Name</param> /// <param name="isShoppingCart">Shopping cart flag</param> /// <returns>Collection of shopping cart items</returns> public IList<CartItemInfo> GetCartItems(string userName, string appName, bool isShoppingCart) { string sqlSelect = "SELECT Cart.ItemId, Cart.Name, Cart.Type, Cart.Price, Cart.CategoryId, Cart.ProductId, Cart.Quantity FROM Profiles INNER JOIN Cart ON Profiles.UniqueID = Cart.UniqueID WHERE Profiles.Username = @Username AND Profiles.ApplicationName = @ApplicationName AND IsShoppingCart = @IsShoppingCart;"; SqlParameter[] parms = { new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256), new SqlParameter("@IsShoppingCart", SqlDbType.Bit)}; parms[0].Value = userName; parms[1].Value = appName; parms[2].Value = isShoppingCart; SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlSelect, parms); IList<CartItemInfo> cartItems = new List<CartItemInfo>(); while(dr.Read()) { CartItemInfo cartItem = new CartItemInfo(dr.GetString(0), dr.GetString(1), dr.GetInt32(6), dr.GetDecimal(3), dr.GetString(2), dr.GetString(4), dr.GetString(5)); cartItems.Add(cartItem); } dr.Close(); return cartItems; } /// <summary> /// Update shopping cart for current user /// </summary> /// <param name="uniqueID">User id</param> /// <param name="cartItems">Collection of shopping cart items</param> /// <param name="isShoppingCart">Shopping cart flag</param> public void SetCartItems(int uniqueID, ICollection<CartItemInfo> cartItems, bool isShoppingCart) { string sqlDelete = "DELETE FROM Cart WHERE UniqueID = @UniqueID AND IsShoppingCart = @IsShoppingCart;"; SqlParameter[] parms1 = { new SqlParameter("@UniqueID", SqlDbType.Int), new SqlParameter("@IsShoppingCart", SqlDbType.Bit)}; parms1[0].Value = uniqueID; parms1[1].Value = isShoppingCart; if (cartItems.Count > 0) { // update cart using SqlTransaction string sqlInsert = "INSERT INTO Cart (UniqueID, ItemId, Name, Type, Price, CategoryId, ProductId, IsShoppingCart, Quantity) VALUES (@UniqueID, @ItemId, @Name, @Type, @Price, @CategoryId, @ProductId, @IsShoppingCart, @Quantity);"; SqlParameter[] parms2 = { new SqlParameter("@UniqueID", SqlDbType.Int), new SqlParameter("@IsShoppingCart", SqlDbType.Bit), new SqlParameter("@ItemId", SqlDbType.VarChar, 10), new SqlParameter("@Name", SqlDbType.VarChar, 80), new SqlParameter("@Type", SqlDbType.VarChar, 80), new SqlParameter("@Price", SqlDbType.Decimal, 8), new SqlParameter("@CategoryId", SqlDbType.VarChar, 10), new SqlParameter("@ProductId", SqlDbType.VarChar, 10), new SqlParameter("@Quantity", SqlDbType.Int)}; parms2[0].Value = uniqueID; parms2[1].Value = isShoppingCart; SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringProfile); conn.Open(); SqlTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted); try { SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sqlDelete, parms1); foreach (CartItemInfo cartItem in cartItems) { parms2[2].Value = cartItem.ItemId; parms2[3].Value = cartItem.Name; parms2[4].Value = cartItem.Type; parms2[5].Value = cartItem.Price; parms2[6].Value = cartItem.CategoryId; parms2[7].Value = cartItem.ProductId; parms2[8].Value = cartItem.Quantity; SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sqlInsert, parms2); } trans.Commit(); } catch (Exception e) { trans.Rollback(); throw new ApplicationException(e.Message); } finally { conn.Close(); } } else // delete cart SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlDelete, parms1); } /// <summary> /// Update activity dates for current user and application /// </summary> /// <param name="userName">USer name</param> /// <param name="activityOnly">Activity only flag</param> /// <param name="appName">Application Name</param> public void UpdateActivityDates(string userName, bool activityOnly, string appName) { DateTime activityDate = DateTime.Now; string sqlUpdate; SqlParameter[] parms; if(activityOnly) { sqlUpdate = "UPDATE Profiles Set LastActivityDate = @LastActivityDate WHERE Username = @Username AND ApplicationName = @ApplicationName;"; parms = new SqlParameter[]{ new SqlParameter("@LastActivityDate", SqlDbType.DateTime), new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256)}; parms[0].Value = activityDate; parms[1].Value = userName; parms[2].Value = appName; } else { sqlUpdate = "UPDATE Profiles Set LastActivityDate = @LastActivityDate, LastUpdatedDate = @LastUpdatedDate WHERE Username = @Username AND ApplicationName = @ApplicationName;"; parms = new SqlParameter[]{ new SqlParameter("@LastActivityDate", SqlDbType.DateTime), new SqlParameter("@LastUpdatedDate", SqlDbType.DateTime), new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256)}; parms[0].Value = activityDate; parms[1].Value = activityDate; parms[2].Value = userName; parms[3].Value = appName; } SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlUpdate, parms); } /// <summary> /// Retrive unique id for current user /// </summary> /// <param name="userName">User name</param> /// <param name="isAuthenticated">Authentication flag</param> /// <param name="ignoreAuthenticationType">Ignore authentication flag</param> /// <param name="appName">Application Name</param> /// <returns>Unique id for current user</returns> public int GetUniqueID(string userName, bool isAuthenticated, bool ignoreAuthenticationType, string appName) { string sqlSelect = "SELECT UniqueID FROM Profiles WHERE Username = @Username AND ApplicationName = @ApplicationName"; SqlParameter[] parms = { new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256)}; parms[0].Value = userName; parms[1].Value = appName; if(!ignoreAuthenticationType) { sqlSelect += " AND IsAnonymous = @IsAnonymous"; Array.Resize<SqlParameter>(ref parms, parms.Length + 1); parms[2] = new SqlParameter("@IsAnonymous", SqlDbType.Bit); parms[2].Value = !isAuthenticated; } int uniqueID = 0; object retVal = null; retVal = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlSelect, parms); if(retVal == null) uniqueID = CreateProfileForUser(userName, isAuthenticated, appName); else uniqueID = Convert.ToInt32(retVal); return uniqueID; } /// <summary> /// Create profile record for current user /// </summary> /// <param name="userName">User name</param> /// <param name="isAuthenticated">Authentication flag</param> /// <param name="appName">Application Name</param> /// <returns>Number of records created</returns> public int CreateProfileForUser(string userName, bool isAuthenticated, string appName) { string sqlInsert = "INSERT INTO Profiles (Username, ApplicationName, LastActivityDate, LastUpdatedDate, IsAnonymous) Values(@Username, @ApplicationName, @LastActivityDate, @LastUpdatedDate, @IsAnonymous); SELECT @@IDENTITY;"; SqlParameter[] parms = { new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256), new SqlParameter("@LastActivityDate", SqlDbType.DateTime), new SqlParameter("@LastUpdatedDate", SqlDbType.DateTime), new SqlParameter("@IsAnonymous", SqlDbType.Bit)}; parms[0].Value = userName; parms[1].Value = appName; parms[2].Value = DateTime.Now; parms[3].Value = DateTime.Now; parms[4].Value = !isAuthenticated; int uniqueID = 0; int.TryParse(SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlInsert, parms).ToString(), out uniqueID); return uniqueID; } /// <summary> /// Retrieve colection of inactive user id's /// </summary> /// <param name="authenticationOption">Authentication option</param> /// <param name="userInactiveSinceDate">Date to start search from</param> /// <param name="appName">Application Name</param> /// <returns>Collection of inactive profile id's</returns> public IList<string> GetInactiveProfiles(int authenticationOption, DateTime userInactiveSinceDate, string appName) { StringBuilder sqlSelect = new StringBuilder("SELECT Username FROM Profiles WHERE ApplicationName = @ApplicationName AND LastActivityDate <= @LastActivityDate"); SqlParameter[] parms = { new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256), new SqlParameter("@LastActivityDate", SqlDbType.DateTime)}; parms[0].Value = appName; parms[1].Value = userInactiveSinceDate; switch(authenticationOption) { case AUTH_ANONYMOUS: sqlSelect.Append(" AND IsAnonymous = @IsAnonymous"); Array.Resize<SqlParameter>(ref parms, parms.Length + 1); parms[2] = new SqlParameter("@IsAnonymous", SqlDbType.Bit); parms[2].Value = true; break; case AUTH_AUTHENTICATED: sqlSelect.Append(" AND IsAnonymous = @IsAnonymous"); Array.Resize<SqlParameter>(ref parms, parms.Length + 1); parms[2] = new SqlParameter("@IsAnonymous", SqlDbType.Bit); parms[2].Value = false; break; default: break; } IList<string> usernames = new List<string>(); SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlSelect.ToString(), parms); while(dr.Read()) { usernames.Add(dr.GetString(0)); } dr.Close(); return usernames; } /// <summary> /// Delete user's profile /// </summary> /// <param name="userName">User name</param> /// <param name="appName">Application Name</param> /// <returns>True, if profile successfully deleted</returns> public bool DeleteProfile(string userName, string appName) { int uniqueID = GetUniqueID(userName, false, true, appName); string sqlDelete = "DELETE FROM Profiles WHERE UniqueID = @UniqueID;"; SqlParameter param = new SqlParameter("@UniqueId", SqlDbType.Int, 4); param.Value = uniqueID; int numDeleted = SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlDelete, param); if(numDeleted <= 0) return false; else return true; } /// <summary> /// Retrieve profile information /// </summary> /// <param name="authenticationOption">Authentication option</param> /// <param name="usernameToMatch">User name</param> /// <param name="userInactiveSinceDate">Date to start search from</param> /// <param name="appName">Application Name</param> /// <param name="totalRecords">Number of records to return</param> /// <returns>Collection of profiles</returns> public IList<CustomProfileInfo> GetProfileInfo(int authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, string appName, out int totalRecords) { // Retrieve the total count. StringBuilder sqlSelect1 = new StringBuilder("SELECT COUNT(*) FROM Profiles WHERE ApplicationName = @ApplicationName"); SqlParameter[] parms1 = { new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256)}; parms1[0].Value = appName; // Retrieve the profile data. StringBuilder sqlSelect2 = new StringBuilder("SELECT Username, LastActivityDate, LastUpdatedDate, IsAnonymous FROM Profiles WHERE ApplicationName = @ApplicationName"); SqlParameter[] parms2 = { new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256) }; parms2[0].Value = appName; int arraySize; // If searching for a user name to match, add the command text and parameters. if(usernameToMatch != null) { arraySize = parms1.Length; sqlSelect1.Append(" AND Username LIKE @Username "); Array.Resize<SqlParameter>(ref parms1, arraySize + 1); parms1[arraySize] = new SqlParameter("@Username", SqlDbType.VarChar, 256); parms1[arraySize].Value = usernameToMatch; sqlSelect2.Append(" AND Username LIKE @Username "); Array.Resize<SqlParameter>(ref parms2, arraySize + 1); parms2[arraySize] = new SqlParameter("@Username", SqlDbType.VarChar, 256); parms2[arraySize].Value = usernameToMatch; } // If searching for inactive profiles, // add the command text and parameters. if(userInactiveSinceDate != null) { arraySize = parms1.Length; sqlSelect1.Append(" AND LastActivityDate >= @LastActivityDate "); Array.Resize<SqlParameter>(ref parms1, arraySize + 1); parms1[arraySize] = new SqlParameter("@LastActivityDate", SqlDbType.DateTime); parms1[arraySize].Value = (DateTime)userInactiveSinceDate; sqlSelect2.Append(" AND LastActivityDate >= @LastActivityDate "); Array.Resize<SqlParameter>(ref parms2, arraySize + 1); parms2[arraySize] = new SqlParameter("@LastActivityDate", SqlDbType.DateTime); parms2[arraySize].Value = (DateTime)userInactiveSinceDate; } // If searching for a anonymous or authenticated profiles, // add the command text and parameters. if(authenticationOption != AUTH_ALL) { arraySize = parms1.Length; Array.Resize<SqlParameter>(ref parms1, arraySize + 1); sqlSelect1.Append(" AND IsAnonymous = @IsAnonymous"); parms1[arraySize] = new SqlParameter("@IsAnonymous", SqlDbType.Bit); Array.Resize<SqlParameter>(ref parms2, arraySize + 1); sqlSelect2.Append(" AND IsAnonymous = @IsAnonymous"); parms2[arraySize] = new SqlParameter("@IsAnonymous", SqlDbType.Bit); switch(authenticationOption) { case AUTH_ANONYMOUS: parms1[arraySize].Value = true; parms2[arraySize].Value = true; break; case AUTH_AUTHENTICATED: parms1[arraySize].Value = false; parms2[arraySize].Value = false; break; default: break; } } IList<CustomProfileInfo> profiles = new List<CustomProfileInfo>(); // Get the profile count. totalRecords = (int)SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlSelect1.ToString(), parms1); // No profiles found. if(totalRecords <= 0) return profiles; SqlDataReader dr; dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.Text, sqlSelect2.ToString(), parms2); while(dr.Read()) { CustomProfileInfo profile = new CustomProfileInfo(dr.GetString(0), dr.GetDateTime(1), dr.GetDateTime(2), dr.GetBoolean(3)); profiles.Add(profile); } dr.Close(); return profiles; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using OpenSim.Framework.ServiceAuth; namespace OpenSim.Server.Handlers.GridUser { public class GridUserServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IGridUserService m_GridUserService; public GridUserServerPostHandler(IGridUserService service, IServiceAuth auth) : base("POST", "/griduser", auth) { m_GridUserService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); string method = string.Empty; try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); method = request["METHOD"].ToString(); switch (method) { case "loggedin": return LoggedIn(request); case "loggedout": return LoggedOut(request); case "sethome": return SetHome(request); case "setposition": return SetPosition(request); case "getgriduserinfo": return GetGridUserInfo(request); case "getgriduserinfos": return GetGridUserInfos(request); } m_log.DebugFormat("[GRID USER HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[GRID USER HANDLER]: Exception in method {0}: {1}", method, e); } return FailureResult(); } byte[] LoggedIn(Dictionary<string, object> request) { string user = String.Empty; if (!request.ContainsKey("UserID")) return FailureResult(); user = request["UserID"].ToString(); GridUserInfo guinfo = m_GridUserService.LoggedIn(user); Dictionary<string, object> result = new Dictionary<string, object>(); result["result"] = guinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID USER HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] LoggedOut(Dictionary<string, object> request) { string userID = string.Empty; UUID regionID = UUID.Zero; Vector3 position = Vector3.Zero; Vector3 lookat = Vector3.Zero; if (!UnpackArgs(request, out userID, out regionID, out position, out lookat)) return FailureResult(); if (m_GridUserService.LoggedOut(userID, UUID.Zero, regionID, position, lookat)) return SuccessResult(); return FailureResult(); } byte[] SetHome(Dictionary<string, object> request) { string user = string.Empty; UUID region = UUID.Zero; Vector3 position = new Vector3(128, 128, 70); Vector3 look = Vector3.Zero; if (!UnpackArgs(request, out user, out region, out position, out look)) return FailureResult(); if (m_GridUserService.SetHome(user, region, position, look)) return SuccessResult(); return FailureResult(); } byte[] SetPosition(Dictionary<string, object> request) { string user = string.Empty; UUID region = UUID.Zero; Vector3 position = new Vector3(128, 128, 70); Vector3 look = Vector3.Zero; if (!request.ContainsKey("UserID") || !request.ContainsKey("RegionID")) return FailureResult(); if (!UnpackArgs(request, out user, out region, out position, out look)) return FailureResult(); if (m_GridUserService.SetLastPosition(user, UUID.Zero, region, position, look)) return SuccessResult(); return FailureResult(); } byte[] GetGridUserInfo(Dictionary<string, object> request) { string user = String.Empty; if (!request.ContainsKey("UserID")) return FailureResult(); user = request["UserID"].ToString(); GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(user); Dictionary<string, object> result = new Dictionary<string, object>(); if (guinfo != null) result["result"] = guinfo.ToKeyValuePairs(); else result["result"] = "null"; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID USER HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetGridUserInfos(Dictionary<string, object> request) { string[] userIDs; if (!request.ContainsKey("AgentIDs")) { m_log.DebugFormat("[GRID USER HANDLER]: GetGridUserInfos called without required uuids argument"); return FailureResult(); } if (!(request["AgentIDs"] is List<string>)) { m_log.DebugFormat("[GRID USER HANDLER]: GetGridUserInfos input argument was of unexpected type {0}", request["uuids"].GetType().ToString()); return FailureResult(); } userIDs = ((List<string>)request["AgentIDs"]).ToArray(); GridUserInfo[] pinfos = m_GridUserService.GetGridUserInfo(userIDs); Dictionary<string, object> result = new Dictionary<string, object>(); if ((pinfos == null) || ((pinfos != null) && (pinfos.Length == 0))) result["result"] = "null"; else { int i = 0; foreach (GridUserInfo pinfo in pinfos) { Dictionary<string, object> rinfoDict = pinfo.ToKeyValuePairs(); result["griduser" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private bool UnpackArgs(Dictionary<string, object> request, out string user, out UUID region, out Vector3 position, out Vector3 lookAt) { user = string.Empty; region = UUID.Zero; position = new Vector3(128, 128, 70); lookAt = Vector3.Zero; if (!request.ContainsKey("UserID") || !request.ContainsKey("RegionID")) return false; user = request["UserID"].ToString(); if (!UUID.TryParse(request["RegionID"].ToString(), out region)) return false; if (request.ContainsKey("Position")) Vector3.TryParse(request["Position"].ToString(), out position); if (request.ContainsKey("LookAt")) Vector3.TryParse(request["LookAt"].ToString(), out lookAt); return true; } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] FailureResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } } }
//------------------------------------------------------------------------------ // <copyright file="AuthenticationManagerBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Globalization; using System.Net.Configuration; using System.Reflection; using System.Security.Authentication.ExtendedProtection; using System.Security.Permissions; using System; using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; internal abstract class AuthenticationManagerBase : IAuthenticationManager { private static volatile ICredentialPolicy s_ICredentialPolicy; private static SpnDictionary m_SpnDictionary = new SpnDictionary(); private static TriState s_OSSupportsExtendedProtection = TriState.Unspecified; private static TriState s_SspSupportsExtendedProtection = TriState.Unspecified; public ICredentialPolicy CredentialPolicy { get { return s_ICredentialPolicy; } set { s_ICredentialPolicy = value; } } public virtual void EnsureConfigLoaded() { // No-op: performed at object creation. } public StringDictionary CustomTargetNameDictionary { get { return m_SpnDictionary; } } // // This will give access to some internal methods // public SpnDictionary SpnDictionary { get { return m_SpnDictionary; } } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] public bool OSSupportsExtendedProtection { get { if (s_OSSupportsExtendedProtection == TriState.Unspecified) { if (ComNetOS.IsWin7orLater) { s_OSSupportsExtendedProtection = TriState.True; } else { if (SspSupportsExtendedProtection) { // EP is considered supported only if both SSPs and http.sys support CBT/EP. // We don't support scenarios where e.g. only SSPs support CBT. In such cases // the customer needs to patch also http.sys (even if he may not use it). if (UnsafeNclNativeMethods.HttpApi.ExtendedProtectionSupported) { s_OSSupportsExtendedProtection = TriState.True; } else { s_OSSupportsExtendedProtection = TriState.False; } } else { s_OSSupportsExtendedProtection = TriState.False; } } } return (s_OSSupportsExtendedProtection == TriState.True); } } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] public bool SspSupportsExtendedProtection { get { if (s_SspSupportsExtendedProtection == TriState.Unspecified) { if (ComNetOS.IsWin7orLater) { s_SspSupportsExtendedProtection = TriState.True; } else { // Perform a loopback NTLM authentication to determine whether the underlying OS supports // extended protection ContextFlags clientFlags = ContextFlags.Connection | ContextFlags.InitIdentify; NTAuthentication client = new NTAuthentication(false, NtlmClient.AuthType, SystemNetworkCredential.defaultCredential, "http/localhost", clientFlags, null); try { NTAuthentication server = new NTAuthentication(true, NtlmClient.AuthType, SystemNetworkCredential.defaultCredential, null, ContextFlags.Connection, null); try { SecurityStatus status; byte[] blob = null; while (!server.IsCompleted) { blob = client.GetOutgoingBlob(blob, true, out status); blob = server.GetOutgoingBlob(blob, true, out status); } if (server.OSSupportsExtendedProtection) { s_SspSupportsExtendedProtection = TriState.True; } else { if (Logging.On) Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_ssp_dont_support_cbt)); s_SspSupportsExtendedProtection = TriState.False; } } finally { server.CloseContext(); } } finally { client.CloseContext(); } } } return (s_SspSupportsExtendedProtection == TriState.True); } } /// <devdoc> /// <para>Call each registered authentication module to determine the first module that /// can respond to the authentication request.</para> /// </devdoc> public abstract Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials); // These four authentication modules require a Channel Binding Token to be able to preauthenticate over https. // After a successful authentication, they will cache the CBT used on the ServicePoint. In order to PreAuthenticate, // they require that a CBT has previously been cached. Any other module should be allowed to try preauthentication // without a cached CBT #if DEBUG // This method is only called as part of an assert protected static bool ModuleRequiresChannelBinding(IAuthenticationModule authenticationModule) { return (authenticationModule is NtlmClient || authenticationModule is KerberosClient || authenticationModule is NegotiateClient || authenticationModule is DigestClient); } #endif /// <devdoc> /// <para>Pre-authenticates a request.</para> /// </devdoc> public abstract Authorization PreAuthenticate(WebRequest request, ICredentials credentials); /// <devdoc> /// <para>Registers an authentication module with the authentication manager.</para> /// </devdoc> public abstract void Register(IAuthenticationModule authenticationModule); /// <devdoc> /// <para>Unregisters authentication modules for an authentication scheme.</para> /// </devdoc> public abstract void Unregister(IAuthenticationModule authenticationModule); /// <devdoc> /// <para>Unregisters authentication modules for an authentication scheme.</para> /// </devdoc> public abstract void Unregister(string authenticationScheme); /// <devdoc> /// <para> /// Returns a list of registered authentication modules. /// </para> /// </devdoc> public abstract IEnumerator RegisteredModules { get; } /// <devdoc> /// <para> /// Binds an authentication response to a request for pre-authentication. /// </para> /// </devdoc> // Create binding between an authorization response and the module // generating that response // This association is used for deciding which module to invoke // for preauthentication purposes public abstract void BindModule(Uri uri, Authorization response, IAuthenticationModule module); // This function returns a prefix of the given absolute Uri // which will be used for associating authentication information // The purpose is to associate the module-binding not with a single // Uri but some collection generalizing that Uri to the loosely-defined // notion of "protection realm" protected static string generalize(Uri location) { string completeUri = location.GetComponents(UriComponents.AbsoluteUri & ~(UriComponents.Query | UriComponents.Fragment), UriFormat.UriEscaped); int lastFwdSlash = completeUri.LastIndexOf('/'); if (lastFwdSlash < 0) { return completeUri; } return completeUri.Substring(0, lastFwdSlash + 1); } }; // class AuthenticationManagerBase } // namespace System.Net
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // <OWNER>[....]</OWNER> /*============================================================================= ** ** Class: WaitHandle (this name is NOT definitive) ** ** ** Purpose: Class to represent all synchronization objects in the runtime (that allow multiple wait) ** ** =============================================================================*/ using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.Threading { using System.Threading; using System.Runtime.Remoting; using System; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_REMOTING public abstract partial class WaitHandle : MarshalByRefObject, IDisposable { #else // FEATURE_REMOTING public abstract partial class WaitHandle : IDisposable { #endif // FEATURE_REMOTING public const int WaitTimeout = 0x102; private const int MAX_WAITHANDLES = 64; #pragma warning disable 414 // Field is not used from managed. private IntPtr waitHandle; // !!! DO NOT MOVE THIS FIELD. (See defn of WAITHANDLEREF in object.h - has hardcoded access to this field.) #pragma warning restore 414 [System.Security.SecurityCritical] // auto-generated internal volatile SafeWaitHandle safeWaitHandle; internal bool hasThreadAffinity; [System.Security.SecuritySafeCritical] // auto-generated private static IntPtr GetInvalidHandle() { return Win32Native.INVALID_HANDLE_VALUE; } protected static readonly IntPtr InvalidHandle = GetInvalidHandle(); private const int WAIT_OBJECT_0 = 0; private const int WAIT_ABANDONED = 0x80; private const int WAIT_FAILED = 0x7FFFFFFF; private const int ERROR_TOO_MANY_POSTS = 0x12A; internal enum OpenExistingResult { Success, NameNotFound, PathNotFound, NameInvalid } protected WaitHandle() { Init(); } [System.Security.SecuritySafeCritical] // auto-generated private void Init() { safeWaitHandle = null; waitHandle = InvalidHandle; hasThreadAffinity = false; } [Obsolete("Use the SafeWaitHandle property instead.")] public virtual IntPtr Handle { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle();} [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] set { if (value == InvalidHandle) { // This line leaks a handle. However, it's currently // not perfectly clear what the right behavior is here // anyways. This preserves Everett behavior. We should // ideally do these things: // *) Expose a settable SafeHandle property on WaitHandle. // *) Expose a settable OwnsHandle property on SafeHandle. // We're looking into this. -- [....] if (safeWaitHandle != null) { safeWaitHandle.SetHandleAsInvalid(); safeWaitHandle = null; } } else { safeWaitHandle = new SafeWaitHandle(value, true); } waitHandle = value; } } public SafeWaitHandle SafeWaitHandle { [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] get { if (safeWaitHandle == null) { safeWaitHandle = new SafeWaitHandle(InvalidHandle, false); } return safeWaitHandle; } [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { // Set safeWaitHandle and waitHandle in a CER so we won't take // a thread abort between the statements and leave the wait // handle in an invalid state. Note this routine is not thread // safe however. RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (value == null) { safeWaitHandle = null; waitHandle = InvalidHandle; } else { safeWaitHandle = value; waitHandle = safeWaitHandle.DangerousGetHandle(); } } } } // Assembly-private version that doesn't do a security check. Reduces the // number of link-time security checks when reading & writing to a file, // and helps avoid a link time check while initializing security (If you // call a Serialization method that requires security before security // has started up, the link time check will start up security, run // serialization code for some security attribute stuff, call into // FileStream, which will then call Sethandle, which requires a link time // security check.). While security has fixed that problem, we still // don't need to do a linktime check here. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal void SetHandleInternal(SafeWaitHandle handle) { safeWaitHandle = handle; waitHandle = handle.DangerousGetHandle(); } public virtual bool WaitOne (int millisecondsTimeout, bool exitContext) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); return WaitOne((long)millisecondsTimeout,exitContext); } public virtual bool WaitOne (TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitOne(tm,exitContext); } public virtual bool WaitOne () { //Infinite Timeout return WaitOne(-1,false); } public virtual bool WaitOne(int millisecondsTimeout) { return WaitOne(millisecondsTimeout, false); } public virtual bool WaitOne(TimeSpan timeout) { return WaitOne(timeout, false); } [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] private bool WaitOne(long timeout, bool exitContext) { return InternalWaitOne(safeWaitHandle, timeout, hasThreadAffinity, exitContext); } [System.Security.SecurityCritical] // auto-generated internal static bool InternalWaitOne(SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext) { if (waitableSafeHandle == null) { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); } Contract.EndContractBlock(); int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext); if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } [System.Security.SecurityCritical] internal bool WaitOneWithoutFAS() { // version of waitone without fast application switch (FAS) support // This is required to support the Wait which FAS needs (otherwise recursive dependency comes in) if (safeWaitHandle == null) { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); } Contract.EndContractBlock(); long timeout = -1; int ret = WaitOneNative(safeWaitHandle, (uint)timeout, hasThreadAffinity, false); if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext); /*======================================================================== ** Waits for signal from all the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when all the object have been pulsed ** or timeout milliseonds have elapsed. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll); [System.Security.SecuritySafeCritical] // auto-generated public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles == null) { throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_Waithandles")); } if(waitHandles.Length == 0) { // // Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct. // Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2, // which went back to ArgumentException. // // Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException // in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking // user code. // #if FEATURE_CORECLR throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); #else throw new ArgumentNullException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); #endif } if (waitHandles.Length > MAX_WAITHANDLES) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles")); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i ++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_ArrayElement")); #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(waitHandle)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); #endif internalWaitHandles[i] = waitHandle; } #if _DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif #if FEATURE_LEGACYNETCF // WinCE did not support "wait all." It turns out that this resulted in NetCF's WaitAll implementation always returning true. // Unfortunately, some apps took a dependency on that, so we have to replicate the behavior here. if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) return true; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/ ); if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret)) { //In the case of WaitAll the OS will only provide the // information that mutex was abandoned. // It won't tell us which one. So we can't set the Index or provide access to the Mutex ThrowAbandonedMutexException(); } GC.KeepAlive(internalWaitHandles); return (ret != WaitTimeout); } public static bool WaitAll( WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitAll(waitHandles,(int)tm, exitContext); } /*======================================================================== ** Shorthand for WaitAll with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ public static bool WaitAll(WaitHandle[] waitHandles) { return WaitAll(waitHandles, Timeout.Infinite, true); } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitAll(waitHandles, millisecondsTimeout, true); } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAll(waitHandles, timeout, true); } /*======================================================================== ** Waits for notification from any of the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when either one of the object have been ** signalled or timeout milliseonds have elapsed. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles==null) { throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_Waithandles")); } if(waitHandles.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); } if (MAX_WAITHANDLES < waitHandles.Length) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles")); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i ++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_ArrayElement")); #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(waitHandle)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); #endif internalWaitHandles[i] = waitHandle; } #if _DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/ ); if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret)) { int mutexIndex = ret -WAIT_ABANDONED; if(0 <= mutexIndex && mutexIndex < internalWaitHandles.Length) { ThrowAbandonedMutexException(mutexIndex,internalWaitHandles[mutexIndex]); } else { ThrowAbandonedMutexException(); } } GC.KeepAlive(internalWaitHandles); return ret; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny( WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitAny(waitHandles,(int)tm, exitContext); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAny(waitHandles, timeout, true); } /*======================================================================== ** Shorthand for WaitAny with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles) { return WaitAny(waitHandles, Timeout.Infinite, true); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitAny(waitHandles, millisecondsTimeout, true); } #if !FEATURE_PAL /*================================================= == == SignalAndWait == ==================================================*/ [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, bool hasThreadAffinity, bool exitContext); public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn) { return SignalAndWait(toSignal,toWaitOn,-1,false); } public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return SignalAndWait(toSignal,toWaitOn,(int)tm,exitContext); } [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext) { if(null == toSignal) { throw new ArgumentNullException("toSignal"); } if(null == toWaitOn) { throw new ArgumentNullException("toWaitOn"); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); //NOTE: This API is not supporting Pause/Resume as it's not exposed in CoreCLR (not in WP or SL) int ret = SignalAndWaitOne(toSignal.safeWaitHandle,toWaitOn.safeWaitHandle,millisecondsTimeout, toWaitOn.hasThreadAffinity,exitContext); if(WAIT_FAILED != ret && toSignal.hasThreadAffinity) { Thread.EndCriticalRegion(); Thread.EndThreadAffinity(); } if(WAIT_ABANDONED == ret) { ThrowAbandonedMutexException(); } if(ERROR_TOO_MANY_POSTS == ret) { throw new InvalidOperationException(Environment.GetResourceString("Threading.WaitHandleTooManyPosts")); } //Object was signaled if(WAIT_OBJECT_0 == ret) { return true; } //Timeout return false; } #endif private static void ThrowAbandonedMutexException() { #if !FEATURE_CORECLR throw new AbandonedMutexException(); #else throw new Exception(Environment.GetResourceString("Threading.AbandonedMutexException")); #endif } private static void ThrowAbandonedMutexException(int location, WaitHandle handle) { #if !FEATURE_CORECLR throw new AbandonedMutexException(location, handle); #else throw new Exception(Environment.GetResourceString("Threading.AbandonedMutexException")); #endif } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] // auto-generated protected virtual void Dispose(bool explicitDisposing) { if (safeWaitHandle != null) { safeWaitHandle.Close(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Runtime.CompilerServices; using DotVVM.Framework.Binding; using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Binding.Properties; using DotVVM.Framework.Compilation; using DotVVM.Framework.Compilation.ControlTree; using DotVVM.Framework.Compilation.Javascript; using DotVVM.Framework.Controls; using DotVVM.Framework.Utils; using Newtonsoft.Json; public static class ValueOrBindingExtensions { /// <summary> Returns the value or the binding from the ValueOrBinding container. Equivalent to calling <code>vob.BindingOrDefault ?? vob.BoxedValue</code> </summary> public static object? UnwrapToObject(this ValueOrBinding vob) => vob.BindingOrDefault ?? vob.BoxedValue; /// <summary> If the obj is ValueOrBinding, returns the binding or the value from the container. Equivalent to <code>obj is ValueOrBinding vob ? vob.UnwrapToObject() : obj</code> </summary> public static object? UnwrapToObject(object? obj) => obj is ValueOrBinding vob ? vob.UnwrapToObject() : obj; /// <summary> Returns ValueOrBinding with the value of `!a`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool> Negate(this ValueOrBinding<bool> v) { if (v.BindingOrDefault is IBinding binding) return new ValueOrBinding<bool>( binding.GetProperty<NegatedBindingExpression>().Binding ); else return new(!v.ValueOrDefault); } /// <summary> Returns ValueOrBinding with the value of `!a`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool?> Negate(this ValueOrBinding<bool?> v) { if (v.BindingOrDefault is IBinding binding) return new ValueOrBinding<bool?>( binding.GetProperty<NegatedBindingExpression>().Binding ); else return new(!v.ValueOrDefault); } /// <summary> Returns a binding with the value of `!bindingValue`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static T Negate<T>(this T binding) where T: IStaticValueBinding<bool> { return (T)binding.GetProperty<NegatedBindingExpression>().Binding; } /// <summary> Returns ValueOrBinding with the value of `a > 0`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool> IsMoreThanZero(this ValueOrBinding<int> v) { if (v.BindingOrDefault is IBinding binding) return new ValueOrBinding<bool>( binding.GetProperty<IsMoreThanZeroBindingProperty>().Binding ); else return new(v.ValueOrDefault > 0); } /// <summary> Returns ValueOrBinding with the value of `a.Items` where a is grid view dataset. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<IList<T>> GetItems<T>(this ValueOrBinding<IBaseGridViewDataSet<T>> v) { if (v.BindingOrDefault is IBinding binding) return new ValueOrBinding<IList<T>>( binding.GetProperty<DataSourceAccessBinding>().Binding ); else return new ValueOrBinding<IList<T>>(v.ValueOrDefault.Items); } /// <summary> Returns ValueOrBinding with the value of `a?.ToString() ?? ""`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<string> AsString<T>(this ValueOrBinding<T> v) { if (v.BindingOrDefault is IBinding binding) return new ValueOrBinding<string>( binding.GetProperty<ExpectedAsStringBindingExpression>().Binding ); else return new ValueOrBinding<string>("" + v.ValueOrDefault); } /// <summary> Returns ValueOrBinding with the value of `a is object`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool> NotNull<T>(this ValueOrBinding<T> v) => v.IsNull().Negate(); /// <summary> Returns ValueOrBinding with the value of `a is null`. The resulting binding is cached, so it should be safe to use this method at runtime. </summary> public static ValueOrBinding<bool> IsNull<T>(this ValueOrBinding<T> v) { if (v.HasBinding) return new(v.BindingOrDefault.GetProperty<IsNullBindingExpression>().Binding); else return new(v.ValueOrDefault is null); } /// <summary> Returns ValueOrBinding with the value of `!string.IsNullOrEmpty(a)`. The resulting binding is cached, so it should be safe to use this method at runtime. </summary> public static ValueOrBinding<bool> NotNullOrEmpty(this ValueOrBinding<string> v) => v.IsNullOrEmpty().Negate(); /// <summary> Returns ValueOrBinding with the value of `string.IsNullOrEmpty(a)`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool> IsNullOrEmpty(this ValueOrBinding<string> v) { if (v.HasBinding) return new(v.BindingOrDefault.GetProperty<IsNullOrEmptyBindingExpression>().Binding); else return new(string.IsNullOrEmpty(v.ValueOrDefault)); } /// <summary> Returns ValueOrBinding with the value of `!string.IsNullOrWhitespace(a)`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool> NotNullOrWhitespace(this ValueOrBinding<string> v) => v.IsNullOrWhitespace().Negate(); /// <summary> Returns ValueOrBinding with the value of `string.IsNullOrWhitespace(a)`. The resulting binding is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool> IsNullOrWhitespace(this ValueOrBinding<string> v) { if (v.HasBinding) return new(v.BindingOrDefault.GetProperty<IsNullOrWhitespaceBindingExpression>().Binding); else return new(string.IsNullOrWhiteSpace(v.ValueOrDefault)); } /// <summary> Returns if the ValueOrBinding contains a value and the value is equal to <paramref name="value"/>. </summary> public static bool ValueEquals<T>(this ValueOrBinding<T> v, [MaybeNull] T value) { if (v.HasBinding) return false; else return EqualityComparer<T>.Default.Equals(v.ValueOrDefault, value); } /// <summary> Returns if the ValueOrBinding contains a value and the value is equal to <paramref name="value"/>. </summary> public static bool ValueEquals<T>(this ValueOrBinding<T> v, [MaybeNull] T value, IEqualityComparer<T> comparer) { if (v.HasBinding) return false; else return comparer.Equals(v.ValueOrDefault, value); } /// <summary> Returns true if the ValueOrBinding contains value, but the value is null. </summary> public static bool ValueIsNull<T>(this ValueOrBinding<T> v) => v.HasValue && v.ValueOrDefault is null; /// <summary> Returns true if the ValueOrBinding contains value, but the value is null or an empty string. </summary> public static bool ValueIsNullOrEmpty(this ValueOrBinding<string> v) => v.HasValue && string.IsNullOrEmpty(v.ValueOrDefault); /// <summary> Returns ValueOrBinding with the value of `a &amp;&amp; b`. If both a and b contain a binding, they are combined together. The result is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool> And(this ValueOrBinding<bool> a, ValueOrBinding<bool> b) { if (a.HasValue) return a.ValueOrDefault ? b : new(false); if (b.HasValue) return b.ValueOrDefault ? a : new(false); return new(BindingCombinator.GetCombination( BindingCombinator.AndAlsoCombination, a.BindingOrDefault, b.BindingOrDefault)); } /// <summary> Returns ValueOrBinding with the value of `a || b`. If both a and b contain a binding, they are combined together. The result is cached, so it's safe to use this method at runtime. </summary> public static ValueOrBinding<bool> Or(this ValueOrBinding<bool> a, ValueOrBinding<bool> b) { if (a.HasValue) return a.ValueOrDefault ? new(true) : b; if (b.HasValue) return b.ValueOrDefault ? new(true) : a; return new(BindingCombinator.GetCombination( BindingCombinator.OrElseCombination, a.BindingOrDefault, b.BindingOrDefault)); } internal static IBinding CreateConstantBinding( object? constant, Type type, BindingCompilationService service, BindingParserOptions bpo) => service.Cache.CreateCachedBinding( "dotvvm-ConstantBinding", new object? [] { type, constant, bpo }, () => { var expr = Expression.Constant(constant, type); return service.CreateBinding(bpo.BindingType, new object[] { bpo, new ExpectedTypeBindingProperty(type), new ResultTypeBindingProperty(type), new ParsedExpressionBindingProperty(expr), new CastedExpressionBindingProperty(expr), new KnockoutJsExpressionBindingProperty(JavascriptTranslationVisitor.TranslateConstant(expr)), new BindingDelegate((_, _) => constant) }); }); internal static IBinding SelectImpl(IBinding binding, LambdaExpression mapping) { var service = binding.GetProperty<BindingCompilationService>(); var parserOptions = binding.GetProperty<BindingParserOptions>(); // get reasonable hash key by captured variables into constants var optimizedExpr = (LambdaExpression)mapping.OptimizeConstants(); if (optimizedExpr.Body is ConstantExpression constantBody) return CreateConstantBinding(constantBody.Value, mapping.ReturnType, service, parserOptions); return service.Cache.CreateCachedBinding( "Dotvvm-BindingSelect", new object[] { new Tuple<IBinding>(binding), new ObjectWithComparer<Expression>(optimizedExpr, ExpressionComparer.Instance) }, () => binding.DeriveBinding( ExpressionUtils.Replace( optimizedExpr, Expression.Convert( binding.GetProperty<ParsedExpressionBindingProperty>().Expression, optimizedExpr.Parameters[0].Type ))) ); } /// <summary> Maps the result of this binding with another expression. The expression is also translated to Javascript, so only translatable methods may be used. /// Note that this method is very fast, so use it carefully. Usage is server-side styles should be preferred over usage at runtime in custom controls. </summary> public static IValueBinding<U> Select<T, U>(this IValueBinding<T> binding, Expression<Func<T, U>> mapping) => (IValueBinding<U>)SelectImpl(binding, mapping); /// <summary> Maps the result of this binding with another expression. The expression is also translated to Javascript, so only translatable methods may be used. /// Note that this method is very fast, so use it carefully. Usage is server-side styles should be preferred over usage at runtime in custom controls. </summary> public static IStaticValueBinding<U> Select<T, U>(this IStaticValueBinding<T> binding, Expression<Func<T, U>> mapping) => (IStaticValueBinding<U>)SelectImpl(binding, mapping); /// <summary> Maps the result of this binding with another expression. The expression is also translated to Javascript, so only translatable methods may be used. /// Note that this method is very fast, so use it carefully. Usage is server-side styles should be preferred over usage at runtime in custom controls. </summary> public static ValueOrBinding<U> Select<T, U>(this ValueOrBinding<T> vob, Expression<Func<T, U>> mapping) => vob.HasBinding ? new(SelectImpl(vob.BindingOrDefault, mapping)) : new(mapping.Compile(preferInterpretation: true).Invoke(vob.ValueOrDefault)); }
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 HomeControl.WebApi.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>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <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 factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private 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 to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified 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) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), 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="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <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, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [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 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. */ #pragma warning disable 618 // Ignore obsolete, we still need to test them. namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity.Rendezvous; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Eviction; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Cache; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.DataStructures.Configuration; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Multicast; using Apache.Ignite.Core.Discovery.Tcp.Static; using Apache.Ignite.Core.Encryption.Keystore; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Tests.Plugin; using Apache.Ignite.Core.Transactions; using NUnit.Framework; using WalMode = Apache.Ignite.Core.PersistentStore.WalMode; /// <summary> /// Tests code-based configuration. /// </summary> public class IgniteConfigurationTest { /// <summary> /// Fixture tear down. /// </summary> [TestFixtureSetUp] public void FixtureTearDown() { Ignition.StopAll(true); } /// <summary> /// Tests the default configuration properties. /// </summary> [Test] public void TestDefaultConfigurationProperties() { CheckDefaultProperties(new IgniteConfiguration()); CheckDefaultProperties(new PersistentStoreConfiguration()); CheckDefaultProperties(new DataStorageConfiguration()); CheckDefaultProperties(new DataRegionConfiguration()); CheckDefaultProperties(new ClientConnectorConfiguration()); CheckDefaultProperties(new SqlConnectorConfiguration()); } /// <summary> /// Tests the default value attributes. /// </summary> [Test] public void TestDefaultValueAttributes() { CheckDefaultValueAttributes(new IgniteConfiguration()); CheckDefaultValueAttributes(new BinaryConfiguration()); CheckDefaultValueAttributes(new TcpDiscoverySpi()); CheckDefaultValueAttributes(new KeystoreEncryptionSpi()); CheckDefaultValueAttributes(new CacheConfiguration()); CheckDefaultValueAttributes(new TcpDiscoveryMulticastIpFinder()); CheckDefaultValueAttributes(new TcpCommunicationSpi()); CheckDefaultValueAttributes(new RendezvousAffinityFunction()); CheckDefaultValueAttributes(new NearCacheConfiguration()); CheckDefaultValueAttributes(new FifoEvictionPolicy()); CheckDefaultValueAttributes(new LruEvictionPolicy()); CheckDefaultValueAttributes(new AtomicConfiguration()); CheckDefaultValueAttributes(new TransactionConfiguration()); CheckDefaultValueAttributes(new MemoryEventStorageSpi()); CheckDefaultValueAttributes(new MemoryConfiguration()); CheckDefaultValueAttributes(new MemoryPolicyConfiguration()); CheckDefaultValueAttributes(new SqlConnectorConfiguration()); CheckDefaultValueAttributes(new ClientConnectorConfiguration()); CheckDefaultValueAttributes(new PersistentStoreConfiguration()); CheckDefaultValueAttributes(new IgniteClientConfiguration()); CheckDefaultValueAttributes(new QueryIndex()); CheckDefaultValueAttributes(new DataStorageConfiguration()); CheckDefaultValueAttributes(new DataRegionConfiguration()); CheckDefaultValueAttributes(new CacheClientConfiguration()); } /// <summary> /// Tests all configuration properties roundtrip to Java and back. /// </summary> [Test] public void TestAllConfigurationProperties() { var cfg = new IgniteConfiguration(GetCustomConfig()); using (var ignite = Ignition.Start(cfg)) { var resCfg = ignite.GetConfiguration(); var disco = (TcpDiscoverySpi) cfg.DiscoverySpi; var resDisco = (TcpDiscoverySpi) resCfg.DiscoverySpi; Assert.AreEqual(disco.NetworkTimeout, resDisco.NetworkTimeout); Assert.AreEqual(disco.AckTimeout, resDisco.AckTimeout); Assert.AreEqual(disco.MaxAckTimeout, resDisco.MaxAckTimeout); Assert.AreEqual(disco.SocketTimeout, resDisco.SocketTimeout); Assert.AreEqual(disco.JoinTimeout, resDisco.JoinTimeout); Assert.AreEqual(disco.LocalAddress, resDisco.LocalAddress); Assert.AreEqual(disco.LocalPort, resDisco.LocalPort); Assert.AreEqual(disco.LocalPortRange, resDisco.LocalPortRange); Assert.AreEqual(disco.ReconnectCount, resDisco.ReconnectCount); Assert.AreEqual(disco.StatisticsPrintFrequency, resDisco.StatisticsPrintFrequency); Assert.AreEqual(disco.ThreadPriority, resDisco.ThreadPriority); Assert.AreEqual(disco.TopologyHistorySize, resDisco.TopologyHistorySize); var enc = (KeystoreEncryptionSpi) cfg.EncryptionSpi; var resEnc = (KeystoreEncryptionSpi) resCfg.EncryptionSpi; Assert.AreEqual(enc.MasterKeyName, resEnc.MasterKeyName); Assert.AreEqual(enc.KeySize, resEnc.KeySize); Assert.AreEqual(enc.KeyStorePath, resEnc.KeyStorePath); Assert.AreEqual(enc.KeyStorePassword, resEnc.KeyStorePassword); var ip = (TcpDiscoveryStaticIpFinder) disco.IpFinder; var resIp = (TcpDiscoveryStaticIpFinder) resDisco.IpFinder; // There can be extra IPv6 endpoints Assert.AreEqual(ip.Endpoints, resIp.Endpoints.Take(2).Select(x => x.Trim('/')).ToArray()); Assert.AreEqual(cfg.IgniteInstanceName, resCfg.IgniteInstanceName); Assert.AreEqual(cfg.IgniteHome, resCfg.IgniteHome); Assert.AreEqual(cfg.IncludedEventTypes, resCfg.IncludedEventTypes); Assert.AreEqual(cfg.MetricsExpireTime, resCfg.MetricsExpireTime); Assert.AreEqual(cfg.MetricsHistorySize, resCfg.MetricsHistorySize); Assert.AreEqual(cfg.MetricsLogFrequency, resCfg.MetricsLogFrequency); Assert.AreEqual(cfg.MetricsUpdateFrequency, resCfg.MetricsUpdateFrequency); Assert.AreEqual(cfg.NetworkSendRetryCount, resCfg.NetworkSendRetryCount); Assert.AreEqual(cfg.NetworkTimeout, resCfg.NetworkTimeout); Assert.AreEqual(cfg.NetworkSendRetryDelay, resCfg.NetworkSendRetryDelay); Assert.AreEqual(cfg.WorkDirectory.Trim(Path.DirectorySeparatorChar), resCfg.WorkDirectory.Trim(Path.DirectorySeparatorChar)); Assert.AreEqual(cfg.JvmClasspath, resCfg.JvmClasspath); Assert.AreEqual(cfg.JvmOptions, resCfg.JvmOptions); Assert.AreEqual(cfg.JvmDllPath, resCfg.JvmDllPath); Assert.AreEqual(cfg.Localhost, resCfg.Localhost); Assert.AreEqual(cfg.IsDaemon, resCfg.IsDaemon); Assert.AreEqual(IgniteConfiguration.DefaultIsLateAffinityAssignment, resCfg.IsLateAffinityAssignment); Assert.AreEqual(cfg.UserAttributes, resCfg.UserAttributes); var atm = cfg.AtomicConfiguration; var resAtm = resCfg.AtomicConfiguration; Assert.AreEqual(atm.AtomicSequenceReserveSize, resAtm.AtomicSequenceReserveSize); Assert.AreEqual(atm.Backups, resAtm.Backups); Assert.AreEqual(atm.CacheMode, resAtm.CacheMode); var tx = cfg.TransactionConfiguration; var resTx = resCfg.TransactionConfiguration; Assert.AreEqual(tx.DefaultTimeout, resTx.DefaultTimeout); Assert.AreEqual(tx.DefaultTransactionConcurrency, resTx.DefaultTransactionConcurrency); Assert.AreEqual(tx.DefaultTransactionIsolation, resTx.DefaultTransactionIsolation); Assert.AreEqual(tx.PessimisticTransactionLogLinger, resTx.PessimisticTransactionLogLinger); Assert.AreEqual(tx.PessimisticTransactionLogSize, resTx.PessimisticTransactionLogSize); Assert.AreEqual(tx.DefaultTimeoutOnPartitionMapExchange, resTx.DefaultTimeoutOnPartitionMapExchange); var com = (TcpCommunicationSpi) cfg.CommunicationSpi; var resCom = (TcpCommunicationSpi) resCfg.CommunicationSpi; Assert.AreEqual(com.AckSendThreshold, resCom.AckSendThreshold); Assert.AreEqual(com.ConnectionsPerNode, resCom.ConnectionsPerNode); Assert.AreEqual(com.ConnectTimeout, resCom.ConnectTimeout); Assert.AreEqual(com.DirectBuffer, resCom.DirectBuffer); Assert.AreEqual(com.DirectSendBuffer, resCom.DirectSendBuffer); Assert.AreEqual(com.FilterReachableAddresses, resCom.FilterReachableAddresses); Assert.AreEqual(com.IdleConnectionTimeout, resCom.IdleConnectionTimeout); Assert.AreEqual(com.LocalAddress, resCom.LocalAddress); Assert.AreEqual(com.LocalPort, resCom.LocalPort); Assert.AreEqual(com.LocalPortRange, resCom.LocalPortRange); Assert.AreEqual(com.MaxConnectTimeout, resCom.MaxConnectTimeout); Assert.AreEqual(com.MessageQueueLimit, resCom.MessageQueueLimit); Assert.AreEqual(com.ReconnectCount, resCom.ReconnectCount); Assert.AreEqual(com.SelectorsCount, resCom.SelectorsCount); Assert.AreEqual(com.SelectorSpins, resCom.SelectorSpins); Assert.AreEqual(com.SharedMemoryPort, resCom.SharedMemoryPort); Assert.AreEqual(com.SlowClientQueueLimit, resCom.SlowClientQueueLimit); Assert.AreEqual(com.SocketReceiveBufferSize, resCom.SocketReceiveBufferSize); Assert.AreEqual(com.SocketSendBufferSize, resCom.SocketSendBufferSize); Assert.AreEqual(com.SocketWriteTimeout, resCom.SocketWriteTimeout); Assert.AreEqual(com.TcpNoDelay, resCom.TcpNoDelay); Assert.AreEqual(com.UnacknowledgedMessagesBufferSize, resCom.UnacknowledgedMessagesBufferSize); Assert.AreEqual(com.UsePairedConnections, resCom.UsePairedConnections); Assert.AreEqual(cfg.FailureDetectionTimeout, resCfg.FailureDetectionTimeout); Assert.AreEqual(cfg.SystemWorkerBlockedTimeout, resCfg.SystemWorkerBlockedTimeout); Assert.AreEqual(cfg.ClientFailureDetectionTimeout, resCfg.ClientFailureDetectionTimeout); Assert.AreEqual(cfg.LongQueryWarningTimeout, resCfg.LongQueryWarningTimeout); Assert.AreEqual(cfg.PublicThreadPoolSize, resCfg.PublicThreadPoolSize); Assert.AreEqual(cfg.StripedThreadPoolSize, resCfg.StripedThreadPoolSize); Assert.AreEqual(cfg.ServiceThreadPoolSize, resCfg.ServiceThreadPoolSize); Assert.AreEqual(cfg.SystemThreadPoolSize, resCfg.SystemThreadPoolSize); Assert.AreEqual(cfg.AsyncCallbackThreadPoolSize, resCfg.AsyncCallbackThreadPoolSize); Assert.AreEqual(cfg.ManagementThreadPoolSize, resCfg.ManagementThreadPoolSize); Assert.AreEqual(cfg.DataStreamerThreadPoolSize, resCfg.DataStreamerThreadPoolSize); Assert.AreEqual(cfg.UtilityCacheThreadPoolSize, resCfg.UtilityCacheThreadPoolSize); Assert.AreEqual(cfg.QueryThreadPoolSize, resCfg.QueryThreadPoolSize); Assert.AreEqual(cfg.ConsistentId, resCfg.ConsistentId); var binCfg = cfg.BinaryConfiguration; Assert.IsFalse(binCfg.CompactFooter); var typ = binCfg.TypeConfigurations.Single(); Assert.AreEqual("myType", typ.TypeName); Assert.IsTrue(typ.IsEnum); Assert.AreEqual("affKey", typ.AffinityKeyFieldName); Assert.AreEqual(false, typ.KeepDeserialized); Assert.IsNotNull(resCfg.PluginConfigurations); Assert.AreEqual(cfg.PluginConfigurations, resCfg.PluginConfigurations); var eventCfg = cfg.EventStorageSpi as MemoryEventStorageSpi; var resEventCfg = resCfg.EventStorageSpi as MemoryEventStorageSpi; Assert.IsNotNull(eventCfg); Assert.IsNotNull(resEventCfg); Assert.AreEqual(eventCfg.ExpirationTimeout, resEventCfg.ExpirationTimeout); Assert.AreEqual(eventCfg.MaxEventCount, resEventCfg.MaxEventCount); var sql = cfg.SqlConnectorConfiguration; var resSql = resCfg.SqlConnectorConfiguration; Assert.AreEqual(sql.Host, resSql.Host); Assert.AreEqual(sql.Port, resSql.Port); Assert.AreEqual(sql.PortRange, resSql.PortRange); Assert.AreEqual(sql.MaxOpenCursorsPerConnection, resSql.MaxOpenCursorsPerConnection); Assert.AreEqual(sql.SocketReceiveBufferSize, resSql.SocketReceiveBufferSize); Assert.AreEqual(sql.SocketSendBufferSize, resSql.SocketSendBufferSize); Assert.AreEqual(sql.TcpNoDelay, resSql.TcpNoDelay); Assert.AreEqual(sql.ThreadPoolSize, resSql.ThreadPoolSize); AssertExtensions.ReflectionEqual(cfg.DataStorageConfiguration, resCfg.DataStorageConfiguration); Assert.AreEqual(cfg.MvccVacuumFrequency, resCfg.MvccVacuumFrequency); Assert.AreEqual(cfg.MvccVacuumThreadCount, resCfg.MvccVacuumThreadCount); Assert.AreEqual(cfg.SqlQueryHistorySize, resCfg.SqlQueryHistorySize); Assert.IsNotNull(resCfg.SqlSchemas); Assert.AreEqual(2, resCfg.SqlSchemas.Count); Assert.IsTrue(resCfg.SqlSchemas.Contains("SCHEMA_3")); Assert.IsTrue(resCfg.SqlSchemas.Contains("schema_4")); Assert.NotNull(cfg.ExecutorConfiguration); AssertExtensions.ReflectionEqual(cfg.ExecutorConfiguration, resCfg.ExecutorConfiguration); } } /// <summary> /// Tests the spring XML. /// </summary> [Test] public void TestSpringXml() { // When Spring XML is used, .NET overrides Spring. var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { DataStorageConfiguration = null, SpringConfigUrl = Path.Combine("Config", "spring-test.xml"), NetworkSendRetryDelay = TimeSpan.FromSeconds(45), MetricsHistorySize = 57 }; using (var ignite = Ignition.Start(cfg)) { var resCfg = ignite.GetConfiguration(); Assert.AreEqual(45, resCfg.NetworkSendRetryDelay.TotalSeconds); // .NET overrides XML Assert.AreEqual(2999, resCfg.NetworkTimeout.TotalMilliseconds); // Not set in .NET -> comes from XML Assert.AreEqual(57, resCfg.MetricsHistorySize); // Only set in .NET var disco = resCfg.DiscoverySpi as TcpDiscoverySpi; Assert.IsNotNull(disco); Assert.AreEqual(TimeSpan.FromMilliseconds(300), disco.SocketTimeout); // DataStorage defaults. CheckDefaultProperties(resCfg.DataStorageConfiguration); CheckDefaultProperties(resCfg.DataStorageConfiguration.DefaultDataRegionConfiguration); // Connector defaults. CheckDefaultProperties(resCfg.ClientConnectorConfiguration); } } /// <summary> /// Tests the client mode. /// </summary> [Test] public void TestClientMode() { using (var ignite = Ignition.Start(new IgniteConfiguration { Localhost = "127.0.0.1", DiscoverySpi = TestUtils.GetStaticDiscovery() })) using (var ignite2 = Ignition.Start(new IgniteConfiguration { Localhost = "127.0.0.1", DiscoverySpi = TestUtils.GetStaticDiscovery(), IgniteInstanceName = "client", ClientMode = true })) { const string cacheName = "cache"; ignite.CreateCache<int, int>(cacheName); Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count); Assert.AreEqual(1, ignite.GetCluster().ForCacheNodes(cacheName).GetNodes().Count); Assert.AreEqual(false, ignite.GetConfiguration().ClientMode); Assert.AreEqual(true, ignite2.GetConfiguration().ClientMode); } } /// <summary> /// Tests the default spi. /// </summary> [Test] public void TestDefaultSpi() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { DiscoverySpi = new TcpDiscoverySpi { AckTimeout = TimeSpan.FromDays(2), MaxAckTimeout = TimeSpan.MaxValue, JoinTimeout = TimeSpan.MaxValue, NetworkTimeout = TimeSpan.MaxValue, SocketTimeout = TimeSpan.MaxValue } }; using (var ignite = Ignition.Start(cfg)) { cfg.IgniteInstanceName = "ignite2"; using (var ignite2 = Ignition.Start(cfg)) { Assert.AreEqual(2, ignite.GetCluster().GetNodes().Count); Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count); } } } /// <summary> /// Tests the invalid timeouts. /// </summary> [Test] public void TestInvalidTimeouts() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { DiscoverySpi = new TcpDiscoverySpi { AckTimeout = TimeSpan.FromMilliseconds(-5), JoinTimeout = TimeSpan.MinValue } }; Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); } /// <summary> /// Tests the static ip finder. /// </summary> [Test] public void TestStaticIpFinder() { TestIpFinders(new TcpDiscoveryStaticIpFinder { Endpoints = new[] {"127.0.0.1:47500"} }, new TcpDiscoveryStaticIpFinder { Endpoints = new[] {"127.0.0.1:47501"} }); } /// <summary> /// Tests the multicast ip finder. /// </summary> [Test] public void TestMulticastIpFinder() { TestIpFinders( new TcpDiscoveryMulticastIpFinder {MulticastGroup = "228.111.111.222", MulticastPort = 54522}, new TcpDiscoveryMulticastIpFinder {MulticastGroup = "228.111.111.223", MulticastPort = 54522}); } /// <summary> /// Tests the work directory. /// </summary> [Test] public void TestWorkDirectory() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { WorkDirectory = PathUtils.GetTempDirectoryName() }; using (Ignition.Start(cfg)) { var marshDir = Path.Combine(cfg.WorkDirectory, "marshaller"); Assert.IsTrue(Directory.Exists(marshDir)); } Directory.Delete(cfg.WorkDirectory, true); } /// <summary> /// Tests the consistent id. /// </summary> [Test] [NUnit.Framework.Category(TestUtils.CategoryIntensive)] public void TestConsistentId() { var ids = new object[] { null, new MyConsistentId {Data = "foo"}, "str", 1, 1.1, DateTime.Now, Guid.NewGuid() }; var cfg = TestUtils.GetTestConfiguration(); foreach (var id in ids) { cfg.ConsistentId = id; using (var ignite = Ignition.Start(cfg)) { Assert.AreEqual(id, ignite.GetConfiguration().ConsistentId); Assert.AreEqual(id ?? "127.0.0.1:47500", ignite.GetCluster().GetLocalNode().ConsistentId); } } } /// <summary> /// Tests the ip finders. /// </summary> /// <param name="ipFinder">The ip finder.</param> /// <param name="ipFinder2">The ip finder2.</param> private static void TestIpFinders(TcpDiscoveryIpFinderBase ipFinder, TcpDiscoveryIpFinderBase ipFinder2) { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { DiscoverySpi = new TcpDiscoverySpi { IpFinder = ipFinder } }; using (var ignite = Ignition.Start(cfg)) { // Start with the same endpoint cfg.IgniteInstanceName = "ignite2"; using (var ignite2 = Ignition.Start(cfg)) { Assert.AreEqual(2, ignite.GetCluster().GetNodes().Count); Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count); } // Start with incompatible endpoint and check that there are 2 topologies ((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder = ipFinder2; using (var ignite2 = Ignition.Start(cfg)) { Assert.AreEqual(1, ignite.GetCluster().GetNodes().Count); Assert.AreEqual(1, ignite2.GetCluster().GetNodes().Count); } } } /// <summary> /// Checks the default properties. /// </summary> /// <param name="cfg">The CFG.</param> private static void CheckDefaultProperties(IgniteConfiguration cfg) { Assert.AreEqual(IgniteConfiguration.DefaultMetricsExpireTime, cfg.MetricsExpireTime); Assert.AreEqual(IgniteConfiguration.DefaultMetricsHistorySize, cfg.MetricsHistorySize); Assert.AreEqual(IgniteConfiguration.DefaultMetricsLogFrequency, cfg.MetricsLogFrequency); Assert.AreEqual(IgniteConfiguration.DefaultMetricsUpdateFrequency, cfg.MetricsUpdateFrequency); Assert.AreEqual(IgniteConfiguration.DefaultNetworkTimeout, cfg.NetworkTimeout); Assert.AreEqual(IgniteConfiguration.DefaultNetworkSendRetryCount, cfg.NetworkSendRetryCount); Assert.AreEqual(IgniteConfiguration.DefaultNetworkSendRetryDelay, cfg.NetworkSendRetryDelay); Assert.AreEqual(IgniteConfiguration.DefaultFailureDetectionTimeout, cfg.FailureDetectionTimeout); Assert.AreEqual(IgniteConfiguration.DefaultClientFailureDetectionTimeout, cfg.ClientFailureDetectionTimeout); Assert.AreEqual(IgniteConfiguration.DefaultLongQueryWarningTimeout, cfg.LongQueryWarningTimeout); Assert.AreEqual(IgniteConfiguration.DefaultIsLateAffinityAssignment, cfg.IsLateAffinityAssignment); Assert.AreEqual(IgniteConfiguration.DefaultIsActiveOnStart, cfg.IsActiveOnStart); Assert.AreEqual(IgniteConfiguration.DefaultClientConnectorConfigurationEnabled, cfg.ClientConnectorConfigurationEnabled); Assert.AreEqual(IgniteConfiguration.DefaultRedirectJavaConsoleOutput, cfg.RedirectJavaConsoleOutput); Assert.AreEqual(IgniteConfiguration.DefaultAuthenticationEnabled, cfg.AuthenticationEnabled); Assert.AreEqual(IgniteConfiguration.DefaultMvccVacuumFrequency, cfg.MvccVacuumFrequency); Assert.AreEqual(IgniteConfiguration.DefaultMvccVacuumThreadCount, cfg.MvccVacuumThreadCount); // Thread pools. Assert.AreEqual(IgniteConfiguration.DefaultManagementThreadPoolSize, cfg.ManagementThreadPoolSize); Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.PublicThreadPoolSize); Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.StripedThreadPoolSize); Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.ServiceThreadPoolSize); Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.SystemThreadPoolSize); Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.AsyncCallbackThreadPoolSize); Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.DataStreamerThreadPoolSize); Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.UtilityCacheThreadPoolSize); Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.QueryThreadPoolSize); } /// <summary> /// Checks the default properties. /// </summary> /// <param name="cfg">Config.</param> private static void CheckDefaultProperties(PersistentStoreConfiguration cfg) { Assert.AreEqual(PersistentStoreConfiguration.DefaultTlbSize, cfg.TlbSize); Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointingFrequency, cfg.CheckpointingFrequency); Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointingThreads, cfg.CheckpointingThreads); Assert.AreEqual(default(long), cfg.CheckpointingPageBufferSize); Assert.AreEqual(PersistentStoreConfiguration.DefaultLockWaitTime, cfg.LockWaitTime); Assert.AreEqual(PersistentStoreConfiguration.DefaultWalFlushFrequency, cfg.WalFlushFrequency); Assert.AreEqual(PersistentStoreConfiguration.DefaultWalFsyncDelayNanos, cfg.WalFsyncDelayNanos); Assert.AreEqual(PersistentStoreConfiguration.DefaultWalHistorySize, cfg.WalHistorySize); Assert.AreEqual(PersistentStoreConfiguration.DefaultWalRecordIteratorBufferSize, cfg.WalRecordIteratorBufferSize); Assert.AreEqual(PersistentStoreConfiguration.DefaultWalSegmentSize, cfg.WalSegmentSize); Assert.AreEqual(PersistentStoreConfiguration.DefaultWalSegments, cfg.WalSegments); Assert.AreEqual(WalMode.Default, cfg.WalMode); Assert.IsFalse(cfg.MetricsEnabled); Assert.AreEqual(PersistentStoreConfiguration.DefaultSubIntervals, cfg.SubIntervals); Assert.AreEqual(PersistentStoreConfiguration.DefaultRateTimeInterval, cfg.RateTimeInterval); Assert.AreEqual(PersistentStoreConfiguration.DefaultWalStorePath, cfg.WalStorePath); Assert.AreEqual(PersistentStoreConfiguration.DefaultWalArchivePath, cfg.WalArchivePath); Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointWriteOrder, cfg.CheckpointWriteOrder); Assert.AreEqual(PersistentStoreConfiguration.DefaultWriteThrottlingEnabled, cfg.WriteThrottlingEnabled); } /// <summary> /// Checks the default properties. /// </summary> /// <param name="cfg">Config.</param> private static void CheckDefaultProperties(DataStorageConfiguration cfg) { Assert.AreEqual(DataStorageConfiguration.DefaultTlbSize, cfg.WalThreadLocalBufferSize); Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointFrequency, cfg.CheckpointFrequency); Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointThreads, cfg.CheckpointThreads); Assert.AreEqual(DataStorageConfiguration.DefaultLockWaitTime, cfg.LockWaitTime); Assert.AreEqual(DataStorageConfiguration.DefaultWalFlushFrequency, cfg.WalFlushFrequency); Assert.AreEqual(DataStorageConfiguration.DefaultWalFsyncDelayNanos, cfg.WalFsyncDelayNanos); Assert.AreEqual(DataStorageConfiguration.DefaultWalHistorySize, cfg.WalHistorySize); Assert.AreEqual(DataStorageConfiguration.DefaultWalRecordIteratorBufferSize, cfg.WalRecordIteratorBufferSize); Assert.AreEqual(DataStorageConfiguration.DefaultWalSegmentSize, cfg.WalSegmentSize); Assert.AreEqual(DataStorageConfiguration.DefaultWalSegments, cfg.WalSegments); Assert.AreEqual(DataStorageConfiguration.DefaultWalMode, cfg.WalMode); Assert.IsFalse(cfg.MetricsEnabled); Assert.AreEqual(DataStorageConfiguration.DefaultMetricsSubIntervalCount, cfg.MetricsSubIntervalCount); Assert.AreEqual(DataStorageConfiguration.DefaultMetricsRateTimeInterval, cfg.MetricsRateTimeInterval); Assert.AreEqual(DataStorageConfiguration.DefaultWalPath, cfg.WalPath); Assert.AreEqual(DataStorageConfiguration.DefaultWalArchivePath, cfg.WalArchivePath); Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointWriteOrder, cfg.CheckpointWriteOrder); Assert.AreEqual(DataStorageConfiguration.DefaultWriteThrottlingEnabled, cfg.WriteThrottlingEnabled); Assert.AreEqual(DataStorageConfiguration.DefaultSystemRegionInitialSize, cfg.SystemRegionInitialSize); Assert.AreEqual(DataStorageConfiguration.DefaultSystemRegionMaxSize, cfg.SystemRegionMaxSize); Assert.AreEqual(DataStorageConfiguration.DefaultPageSize, cfg.PageSize); Assert.AreEqual(DataStorageConfiguration.DefaultConcurrencyLevel, cfg.ConcurrencyLevel); Assert.AreEqual(DataStorageConfiguration.DefaultWalAutoArchiveAfterInactivity, cfg.WalAutoArchiveAfterInactivity); } /// <summary> /// Checks the default properties. /// </summary> /// <param name="cfg">Config.</param> private static void CheckDefaultProperties(DataRegionConfiguration cfg) { Assert.AreEqual(DataRegionConfiguration.DefaultEmptyPagesPoolSize, cfg.EmptyPagesPoolSize); Assert.AreEqual(DataRegionConfiguration.DefaultEvictionThreshold, cfg.EvictionThreshold); Assert.AreEqual(DataRegionConfiguration.DefaultInitialSize, cfg.InitialSize); Assert.AreEqual(DataRegionConfiguration.DefaultMaxSize, cfg.MaxSize); Assert.AreEqual(DataRegionConfiguration.DefaultPersistenceEnabled, cfg.PersistenceEnabled); Assert.AreEqual(DataRegionConfiguration.DefaultMetricsRateTimeInterval, cfg.MetricsRateTimeInterval); Assert.AreEqual(DataRegionConfiguration.DefaultMetricsSubIntervalCount, cfg.MetricsSubIntervalCount); Assert.AreEqual(default(long), cfg.CheckpointPageBufferSize); } /// <summary> /// Checks the default properties. /// </summary> /// <param name="cfg">Config.</param> private static void CheckDefaultProperties(ClientConnectorConfiguration cfg) { Assert.AreEqual(ClientConnectorConfiguration.DefaultPort, cfg.Port); Assert.AreEqual(ClientConnectorConfiguration.DefaultPortRange, cfg.PortRange); Assert.AreEqual(ClientConnectorConfiguration.DefaultMaxOpenCursorsPerConnection, cfg.MaxOpenCursorsPerConnection); Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize); Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize); Assert.AreEqual(ClientConnectorConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay); Assert.AreEqual(ClientConnectorConfiguration.DefaultThreadPoolSize, cfg.ThreadPoolSize); Assert.AreEqual(ClientConnectorConfiguration.DefaultIdleTimeout, cfg.IdleTimeout); Assert.AreEqual(ClientConnectorConfiguration.DefaultThinClientEnabled, cfg.ThinClientEnabled); Assert.AreEqual(ClientConnectorConfiguration.DefaultJdbcEnabled, cfg.JdbcEnabled); Assert.AreEqual(ClientConnectorConfiguration.DefaultOdbcEnabled, cfg.OdbcEnabled); } /// <summary> /// Checks the default properties. /// </summary> /// <param name="cfg">Config.</param> private static void CheckDefaultProperties(SqlConnectorConfiguration cfg) { Assert.AreEqual(ClientConnectorConfiguration.DefaultPort, cfg.Port); Assert.AreEqual(ClientConnectorConfiguration.DefaultPortRange, cfg.PortRange); Assert.AreEqual(ClientConnectorConfiguration.DefaultMaxOpenCursorsPerConnection, cfg.MaxOpenCursorsPerConnection); Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize); Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize); Assert.AreEqual(ClientConnectorConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay); Assert.AreEqual(ClientConnectorConfiguration.DefaultThreadPoolSize, cfg.ThreadPoolSize); } /// <summary> /// Checks the default value attributes. /// </summary> /// <param name="obj">The object.</param> private static void CheckDefaultValueAttributes(object obj) { var props = obj.GetType().GetProperties(); foreach (var prop in props.Where(p => p.Name != "SelectorsCount" && p.Name != "ReadStripesNumber" && !p.Name.Contains("ThreadPoolSize") && p.Name != "MaxSize" && p.Name != "HandshakeTimeout" && p.Name != "ConcurrencyLevel" && p.Name != "Logger")) { var attr = prop.GetCustomAttributes(true).OfType<DefaultValueAttribute>().FirstOrDefault(); var propValue = prop.GetValue(obj, null); if (attr != null) Assert.AreEqual(attr.Value, propValue, string.Format("{0}.{1}", obj.GetType(), prop.Name)); else if (prop.PropertyType.IsValueType) Assert.AreEqual(Activator.CreateInstance(prop.PropertyType), propValue, prop.Name); else Assert.IsNull(propValue); } } /// <summary> /// Gets the custom configuration. /// </summary> private static IgniteConfiguration GetCustomConfig() { // CacheConfiguration is not tested here - see CacheConfigurationTest return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { DiscoverySpi = new TcpDiscoverySpi { NetworkTimeout = TimeSpan.FromSeconds(1), AckTimeout = TimeSpan.FromSeconds(2), MaxAckTimeout = TimeSpan.FromSeconds(3), SocketTimeout = TimeSpan.FromSeconds(4), JoinTimeout = TimeSpan.FromSeconds(5), IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] {"127.0.0.1:49900", "127.0.0.1:49901"} }, ClientReconnectDisabled = true, ForceServerMode = true, IpFinderCleanFrequency = TimeSpan.FromMinutes(7), LocalAddress = "127.0.0.1", LocalPort = 49900, LocalPortRange = 13, ReconnectCount = 11, StatisticsPrintFrequency = TimeSpan.FromSeconds(20), ThreadPriority = 6, TopologyHistorySize = 1234567 }, EncryptionSpi = new KeystoreEncryptionSpi() { KeySize = 192, KeyStorePassword = "love_sex_god", KeyStorePath = "tde.jks", MasterKeyName = KeystoreEncryptionSpi.DefaultMasterKeyName }, IgniteInstanceName = "gridName1", IgniteHome = IgniteHome.Resolve(), IncludedEventTypes = EventType.DiscoveryAll, MetricsExpireTime = TimeSpan.FromMinutes(7), MetricsHistorySize = 125, MetricsLogFrequency = TimeSpan.FromMinutes(8), MetricsUpdateFrequency = TimeSpan.FromMinutes(9), NetworkSendRetryCount = 54, NetworkTimeout = TimeSpan.FromMinutes(10), NetworkSendRetryDelay = TimeSpan.FromMinutes(11), WorkDirectory = Path.GetTempPath(), Localhost = "127.0.0.1", IsDaemon = false, IsLateAffinityAssignment = false, UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(), x => (object) x), AtomicConfiguration = new AtomicConfiguration { CacheMode = CacheMode.Replicated, Backups = 2, AtomicSequenceReserveSize = 200 }, TransactionConfiguration = new TransactionConfiguration { DefaultTransactionConcurrency = TransactionConcurrency.Optimistic, DefaultTimeout = TimeSpan.FromSeconds(25), DefaultTransactionIsolation = TransactionIsolation.Serializable, PessimisticTransactionLogLinger = TimeSpan.FromHours(1), PessimisticTransactionLogSize = 240, DefaultTimeoutOnPartitionMapExchange = TimeSpan.FromSeconds(25) }, CommunicationSpi = new TcpCommunicationSpi { LocalPort = 47501, MaxConnectTimeout = TimeSpan.FromSeconds(34), MessageQueueLimit = 15, ConnectTimeout = TimeSpan.FromSeconds(17), IdleConnectionTimeout = TimeSpan.FromSeconds(19), SelectorsCount = 8, ReconnectCount = 33, SocketReceiveBufferSize = 512, AckSendThreshold = 99, DirectBuffer = false, DirectSendBuffer = true, LocalPortRange = 45, LocalAddress = "127.0.0.1", TcpNoDelay = false, SlowClientQueueLimit = 98, SocketSendBufferSize = 2045, UnacknowledgedMessagesBufferSize = 3450, ConnectionsPerNode = 12, UsePairedConnections = true, SharedMemoryPort = 1234, SocketWriteTimeout = 2222, SelectorSpins = 12, FilterReachableAddresses = true }, FailureDetectionTimeout = TimeSpan.FromSeconds(3.5), SystemWorkerBlockedTimeout = TimeSpan.FromSeconds(8.5), ClientFailureDetectionTimeout = TimeSpan.FromMinutes(12.3), LongQueryWarningTimeout = TimeSpan.FromMinutes(1.23), IsActiveOnStart = true, BinaryConfiguration = new BinaryConfiguration { CompactFooter = false, TypeConfigurations = new[] { new BinaryTypeConfiguration { TypeName = "myType", IsEnum = true, AffinityKeyFieldName = "affKey", KeepDeserialized = false } } }, // Skip cache check because with persistence the grid is not active by default. PluginConfigurations = new[] {new TestIgnitePluginConfiguration {SkipCacheCheck = true}}, EventStorageSpi = new MemoryEventStorageSpi { ExpirationTimeout = TimeSpan.FromSeconds(5), MaxEventCount = 10 }, PublicThreadPoolSize = 3, StripedThreadPoolSize = 5, ServiceThreadPoolSize = 6, SystemThreadPoolSize = 7, AsyncCallbackThreadPoolSize = 8, ManagementThreadPoolSize = 9, DataStreamerThreadPoolSize = 10, UtilityCacheThreadPoolSize = 11, QueryThreadPoolSize = 12, SqlConnectorConfiguration = new SqlConnectorConfiguration { Host = "127.0.0.2", Port = 1081, PortRange = 3, SocketReceiveBufferSize = 2048, MaxOpenCursorsPerConnection = 5, ThreadPoolSize = 4, TcpNoDelay = false, SocketSendBufferSize = 4096 }, ConsistentId = new MyConsistentId {Data = "abc"}, DataStorageConfiguration = new DataStorageConfiguration { AlwaysWriteFullPages = true, CheckpointFrequency = TimeSpan.FromSeconds(25), CheckpointThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), StoragePath = Path.GetTempPath(), WalThreadLocalBufferSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = Configuration.WalMode.LogOnly, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalPath = Path.GetTempPath(), MetricsEnabled = true, MetricsSubIntervalCount = 7, MetricsRateTimeInterval = TimeSpan.FromSeconds(9), CheckpointWriteOrder = Configuration.CheckpointWriteOrder.Random, WriteThrottlingEnabled = true, SystemRegionInitialSize = 64 * 1024 * 1024, SystemRegionMaxSize = 128 * 1024 * 1024, ConcurrencyLevel = 1, PageSize = 8 * 1024, WalAutoArchiveAfterInactivity = TimeSpan.FromMinutes(5), CheckpointReadLockTimeout = TimeSpan.FromSeconds(9.5), DefaultDataRegionConfiguration = new DataRegionConfiguration { Name = "reg1", EmptyPagesPoolSize = 50, EvictionThreshold = 0.8, InitialSize = 100 * 1024 * 1024, MaxSize = 150 * 1024 * 1024, MetricsEnabled = true, PageEvictionMode = Configuration.DataPageEvictionMode.Random2Lru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(2), MetricsSubIntervalCount = 6, SwapPath = PathUtils.GetTempDirectoryName(), CheckpointPageBufferSize = 28 * 1024 * 1024 }, DataRegionConfigurations = new[] { new DataRegionConfiguration { Name = "reg2", EmptyPagesPoolSize = 51, EvictionThreshold = 0.7, InitialSize = 101 * 1024 * 1024, MaxSize = 151 * 1024 * 1024, MetricsEnabled = false, PageEvictionMode = Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(3), MetricsSubIntervalCount = 7, SwapPath = PathUtils.GetTempDirectoryName() } } }, AuthenticationEnabled = false, MvccVacuumFrequency = 20000, MvccVacuumThreadCount = 8, SqlQueryHistorySize = 99, SqlSchemas = new List<string> { "SCHEMA_3", "schema_4" }, ExecutorConfiguration = new[] { new ExecutorConfiguration { Name = "ex-1", Size = 11 } } }; } private class MyConsistentId { public string Data { get; set; } private bool Equals(MyConsistentId other) { return string.Equals(Data, other.Data); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((MyConsistentId) obj); } public override int GetHashCode() { return (Data != null ? Data.GetHashCode() : 0); } public static bool operator ==(MyConsistentId left, MyConsistentId right) { return Equals(left, right); } public static bool operator !=(MyConsistentId left, MyConsistentId right) { return !Equals(left, right); } } } }
namespace Antlr.Runtime { using System.Collections.Generic; using ArgumentException = System.ArgumentException; using Console = System.Console; using Math = System.Math; using DebuggerDisplay = System.Diagnostics.DebuggerDisplayAttribute; using Exception = System.Exception; using StringBuilder = System.Text.StringBuilder; using Type = System.Type; #if !SILVERLIGHT [System.Serializable] #endif [DebuggerDisplay( "TODO: TokenRewriteStream debugger display" )] internal class TokenRewriteStream : CommonTokenStream { public const string DEFAULT_PROGRAM_NAME = "default"; public const int PROGRAM_INIT_SIZE = 100; public const int MIN_TOKEN_INDEX = 0; // Define the rewrite operation hierarchy protected class RewriteOperation { public int instructionIndex; public int index; public object text; // outer protected TokenRewriteStream stream; protected RewriteOperation(TokenRewriteStream stream, int index) { this.stream = stream; this.index = index; } protected RewriteOperation( TokenRewriteStream stream, int index, object text ) { this.index = index; this.text = text; this.stream = stream; } public virtual int Execute( StringBuilder buf ) { return index; } public override string ToString() { string opName = this.GetType().Name; int dindex = opName.IndexOf( '$' ); opName = opName.Substring( dindex + 1 ); return string.Format("<{0}@{1}:\"{2}\">", opName, stream._tokens[index], text); } } private class InsertBeforeOp : RewriteOperation { public InsertBeforeOp( TokenRewriteStream stream, int index, object text ) : base( stream, index, text ) { } public override int Execute( StringBuilder buf ) { buf.Append( text ); if (stream._tokens[index].Type != CharStreamConstants.EndOfFile) buf.Append(stream._tokens[index].Text); return index + 1; } } private class ReplaceOp : RewriteOperation { public int lastIndex; public ReplaceOp( TokenRewriteStream stream, int from, int to, object text ) : base( stream, from, text ) { lastIndex = to; } public override int Execute( StringBuilder buf ) { if ( text != null ) { buf.Append( text ); } return lastIndex + 1; } public override string ToString() { if (text == null) { return string.Format("<DeleteOp@{0}..{1}>", stream._tokens[index], stream._tokens[lastIndex]); } return string.Format("<ReplaceOp@{0}..{1}:\"{2}\">", stream._tokens[index], stream._tokens[lastIndex], text); } } protected IDictionary<string, IList<RewriteOperation>> programs = null; protected IDictionary<string, int> lastRewriteTokenIndexes = null; public TokenRewriteStream() { Init(); } protected void Init() { programs = new Dictionary<string, IList<RewriteOperation>>(); programs[DEFAULT_PROGRAM_NAME] = new List<RewriteOperation>( PROGRAM_INIT_SIZE ); lastRewriteTokenIndexes = new Dictionary<string, int>(); } public TokenRewriteStream( ITokenSource tokenSource ) : base( tokenSource ) { Init(); } public TokenRewriteStream( ITokenSource tokenSource, int channel ) : base( tokenSource, channel ) { Init(); } public virtual void Rollback( int instructionIndex ) { Rollback( DEFAULT_PROGRAM_NAME, instructionIndex ); } public virtual void Rollback( string programName, int instructionIndex ) { IList<RewriteOperation> @is; if ( programs.TryGetValue( programName, out @is ) && @is != null ) { List<RewriteOperation> sublist = new List<RewriteOperation>(); for ( int i = MIN_TOKEN_INDEX; i <= instructionIndex; i++ ) sublist.Add( @is[i] ); programs[programName] = sublist; } } public virtual void DeleteProgram() { DeleteProgram( DEFAULT_PROGRAM_NAME ); } public virtual void DeleteProgram( string programName ) { Rollback( programName, MIN_TOKEN_INDEX ); } public virtual void InsertAfter( IToken t, object text ) { InsertAfter( DEFAULT_PROGRAM_NAME, t, text ); } public virtual void InsertAfter( int index, object text ) { InsertAfter( DEFAULT_PROGRAM_NAME, index, text ); } public virtual void InsertAfter( string programName, IToken t, object text ) { InsertAfter( programName, t.TokenIndex, text ); } public virtual void InsertAfter( string programName, int index, object text ) { // to insert after, just insert before next index (even if past end) InsertBefore( programName, index + 1, text ); } public virtual void InsertBefore( IToken t, object text ) { InsertBefore( DEFAULT_PROGRAM_NAME, t, text ); } public virtual void InsertBefore( int index, object text ) { InsertBefore( DEFAULT_PROGRAM_NAME, index, text ); } public virtual void InsertBefore( string programName, IToken t, object text ) { InsertBefore( programName, t.TokenIndex, text ); } public virtual void InsertBefore( string programName, int index, object text ) { RewriteOperation op = new InsertBeforeOp( this, index, text ); IList<RewriteOperation> rewrites = GetProgram( programName ); op.instructionIndex = rewrites.Count; rewrites.Add( op ); } public virtual void Replace( int index, object text ) { Replace( DEFAULT_PROGRAM_NAME, index, index, text ); } public virtual void Replace( int from, int to, object text ) { Replace( DEFAULT_PROGRAM_NAME, from, to, text ); } public virtual void Replace( IToken indexT, object text ) { Replace( DEFAULT_PROGRAM_NAME, indexT, indexT, text ); } public virtual void Replace( IToken from, IToken to, object text ) { Replace( DEFAULT_PROGRAM_NAME, from, to, text ); } public virtual void Replace( string programName, int from, int to, object text ) { if ( from > to || from < 0 || to < 0 || to >= _tokens.Count ) { throw new ArgumentException( "replace: range invalid: " + from + ".." + to + "(size=" + _tokens.Count + ")" ); } RewriteOperation op = new ReplaceOp( this, from, to, text ); IList<RewriteOperation> rewrites = GetProgram( programName ); op.instructionIndex = rewrites.Count; rewrites.Add( op ); } public virtual void Replace( string programName, IToken from, IToken to, object text ) { Replace( programName, from.TokenIndex, to.TokenIndex, text ); } public virtual void Delete( int index ) { Delete( DEFAULT_PROGRAM_NAME, index, index ); } public virtual void Delete( int from, int to ) { Delete( DEFAULT_PROGRAM_NAME, from, to ); } public virtual void Delete( IToken indexT ) { Delete( DEFAULT_PROGRAM_NAME, indexT, indexT ); } public virtual void Delete( IToken from, IToken to ) { Delete( DEFAULT_PROGRAM_NAME, from, to ); } public virtual void Delete( string programName, int from, int to ) { Replace( programName, from, to, null ); } public virtual void Delete( string programName, IToken from, IToken to ) { Replace( programName, from, to, null ); } public virtual int GetLastRewriteTokenIndex() { return GetLastRewriteTokenIndex( DEFAULT_PROGRAM_NAME ); } protected virtual int GetLastRewriteTokenIndex( string programName ) { int value; if ( lastRewriteTokenIndexes.TryGetValue( programName, out value ) ) return value; return -1; } protected virtual void SetLastRewriteTokenIndex( string programName, int i ) { lastRewriteTokenIndexes[programName] = i; } protected virtual IList<RewriteOperation> GetProgram( string name ) { IList<RewriteOperation> @is; if ( !programs.TryGetValue( name, out @is ) || @is == null ) { @is = InitializeProgram( name ); } return @is; } private IList<RewriteOperation> InitializeProgram( string name ) { IList<RewriteOperation> @is = new List<RewriteOperation>( PROGRAM_INIT_SIZE ); programs[name] = @is; return @is; } public virtual string ToOriginalString() { Fill(); return ToOriginalString( MIN_TOKEN_INDEX, Count - 1 ); } public virtual string ToOriginalString( int start, int end ) { StringBuilder buf = new StringBuilder(); for ( int i = start; i >= MIN_TOKEN_INDEX && i <= end && i < _tokens.Count; i++ ) { if (Get(i).Type != CharStreamConstants.EndOfFile) buf.Append(Get(i).Text); } return buf.ToString(); } public override string ToString() { Fill(); return ToString( MIN_TOKEN_INDEX, Count - 1 ); } public virtual string ToString( string programName ) { Fill(); return ToString(programName, MIN_TOKEN_INDEX, Count - 1); } public override string ToString( int start, int end ) { return ToString( DEFAULT_PROGRAM_NAME, start, end ); } public virtual string ToString( string programName, int start, int end ) { IList<RewriteOperation> rewrites; if ( !programs.TryGetValue( programName, out rewrites ) ) rewrites = null; // ensure start/end are in range if ( end > _tokens.Count - 1 ) end = _tokens.Count - 1; if ( start < 0 ) start = 0; if ( rewrites == null || rewrites.Count == 0 ) { return ToOriginalString( start, end ); // no instructions to execute } StringBuilder buf = new StringBuilder(); // First, optimize instruction stream IDictionary<int, RewriteOperation> indexToOp = ReduceToSingleOperationPerIndex( rewrites ); // Walk buffer, executing instructions and emitting tokens int i = start; while ( i <= end && i < _tokens.Count ) { RewriteOperation op; bool exists = indexToOp.TryGetValue( i, out op ); if ( exists ) { // remove so any left have index size-1 indexToOp.Remove( i ); } if ( !exists || op == null ) { IToken t = _tokens[i]; // no operation at that index, just dump token if (t.Type != CharStreamConstants.EndOfFile) buf.Append(t.Text); i++; // move to next token } else { i = op.Execute( buf ); // execute operation and skip } } // include stuff after end if it's last index in buffer // So, if they did an insertAfter(lastValidIndex, "foo"), include // foo if end==lastValidIndex. if ( end == _tokens.Count - 1 ) { // Scan any remaining operations after last token // should be included (they will be inserts). foreach ( RewriteOperation op in indexToOp.Values ) { if ( op.index >= _tokens.Count - 1 ) buf.Append( op.text ); } } return buf.ToString(); } protected virtual IDictionary<int, RewriteOperation> ReduceToSingleOperationPerIndex( IList<RewriteOperation> rewrites ) { //System.out.println("rewrites="+rewrites); // WALK REPLACES for ( int i = 0; i < rewrites.Count; i++ ) { RewriteOperation op = rewrites[i]; if ( op == null ) continue; if ( !( op is ReplaceOp ) ) continue; ReplaceOp rop = (ReplaceOp)rewrites[i]; // Wipe prior inserts within range var inserts = GetKindOfOps( rewrites, typeof( InsertBeforeOp ), i ); for ( int j = 0; j < inserts.Count; j++ ) { InsertBeforeOp iop = (InsertBeforeOp)inserts[j]; if (iop.index == rop.index) { // E.g., insert before 2, delete 2..2; update replace // text to include insert before, kill insert rewrites[iop.instructionIndex] = null; rop.text = iop.text.ToString() + (rop.text != null ? rop.text.ToString() : string.Empty); } else if (iop.index > rop.index && iop.index <= rop.lastIndex) { // delete insert as it's a no-op. rewrites[iop.instructionIndex] = null; } } // Drop any prior replaces contained within var prevReplaces = GetKindOfOps( rewrites, typeof( ReplaceOp ), i ); for ( int j = 0; j < prevReplaces.Count; j++ ) { ReplaceOp prevRop = (ReplaceOp)prevReplaces[j]; if ( prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex ) { // delete replace as it's a no-op. rewrites[prevRop.instructionIndex] = null; continue; } // throw exception unless disjoint or identical bool disjoint = prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex; bool same = prevRop.index == rop.index && prevRop.lastIndex == rop.lastIndex; // Delete special case of replace (text==null): // D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) if (prevRop.text == null && rop.text == null && !disjoint) { //System.out.println("overlapping deletes: "+prevRop+", "+rop); rewrites[prevRop.instructionIndex] = null; // kill first delete rop.index = Math.Min(prevRop.index, rop.index); rop.lastIndex = Math.Max(prevRop.lastIndex, rop.lastIndex); Console.WriteLine("new rop " + rop); } else if ( !disjoint && !same ) { throw new ArgumentException( "replace op boundaries of " + rop + " overlap with previous " + prevRop ); } } } // WALK INSERTS for ( int i = 0; i < rewrites.Count; i++ ) { RewriteOperation op = (RewriteOperation)rewrites[i]; if ( op == null ) continue; if ( !( op is InsertBeforeOp ) ) continue; InsertBeforeOp iop = (InsertBeforeOp)rewrites[i]; // combine current insert with prior if any at same index var prevInserts = GetKindOfOps( rewrites, typeof( InsertBeforeOp ), i ); for ( int j = 0; j < prevInserts.Count; j++ ) { InsertBeforeOp prevIop = (InsertBeforeOp)prevInserts[j]; if ( prevIop.index == iop.index ) { // combine objects // convert to strings...we're in process of toString'ing // whole token buffer so no lazy eval issue with any templates iop.text = CatOpText( iop.text, prevIop.text ); // delete redundant prior insert rewrites[prevIop.instructionIndex] = null; } } // look for replaces where iop.index is in range; error var prevReplaces = GetKindOfOps( rewrites, typeof( ReplaceOp ), i ); for ( int j = 0; j < prevReplaces.Count; j++ ) { ReplaceOp rop = (ReplaceOp)prevReplaces[j]; if ( iop.index == rop.index ) { rop.text = CatOpText( iop.text, rop.text ); rewrites[i] = null; // delete current insert continue; } if ( iop.index >= rop.index && iop.index <= rop.lastIndex ) { throw new ArgumentException( "insert op " + iop + " within boundaries of previous " + rop ); } } } // System.out.println("rewrites after="+rewrites); IDictionary<int, RewriteOperation> m = new Dictionary<int, RewriteOperation>(); for ( int i = 0; i < rewrites.Count; i++ ) { RewriteOperation op = (RewriteOperation)rewrites[i]; if ( op == null ) continue; // ignore deleted ops RewriteOperation existing; if ( m.TryGetValue( op.index, out existing ) && existing != null ) { throw new Exception( "should only be one op per index" ); } m[op.index] = op; } //System.out.println("index to op: "+m); return m; } protected virtual string CatOpText( object a, object b ) { return string.Concat( a, b ); } protected virtual IList<RewriteOperation> GetKindOfOps( IList<RewriteOperation> rewrites, Type kind ) { return GetKindOfOps( rewrites, kind, rewrites.Count ); } protected virtual IList<RewriteOperation> GetKindOfOps( IList<RewriteOperation> rewrites, Type kind, int before ) { IList<RewriteOperation> ops = new List<RewriteOperation>(); for ( int i = 0; i < before && i < rewrites.Count; i++ ) { RewriteOperation op = rewrites[i]; if ( op == null ) continue; // ignore deleted if ( op.GetType() == kind ) ops.Add( op ); } return ops; } public virtual string ToDebugString() { return ToDebugString( MIN_TOKEN_INDEX, Count - 1 ); } public virtual string ToDebugString( int start, int end ) { StringBuilder buf = new StringBuilder(); for ( int i = start; i >= MIN_TOKEN_INDEX && i <= end && i < _tokens.Count; i++ ) { buf.Append( Get( i ) ); } return buf.ToString(); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; // TODO: Editor UI & Features // - Play animation // - Set frame of animation // - Set time of animation public enum AnimationState { stopped, playing, paused } public enum AnimationStyle { end, reset, loop, pingPong } [Serializable] public class ShapeKeyFrameSequence : System.Object { public float[] strength; } [Serializable] public class ShapeKeyAnimation : System.Object { public string name; public ShapeKeyAnimations parent; public ShapeKeys shapeKeys; public int numberOfFrames = 0; public float frameRate = 24.0f; public float frameDelay { get { return 1.0f/frameRate; } } public float duration { get { return numberOfFrames * frameDelay; } } private float _startTime; public float startTime { get { return _startTime; } } private float _currentTime; public float currentTime { get { // We calculate the current time based on distance from the end, // rather than distance from the start, this helps us deal with // pausing the animation. return duration - (_endTime - _currentTime); } set { // set the time, next update will set the verts _currentTime = value; } } private float _endTime; public float endTime { get { return _endTime; } } public bool hasEnded { get { return (currentTime >= endTime); } } public int currentFrame { get { return (int)Mathf.Floor(currentTime / duration); } set { // Move the animation to the specified frame as a time index. currentTime = value * frameDelay; } } private AnimationState animationState = AnimationState.stopped; public AnimationStyle animationStyle = AnimationStyle.end; public ShapeKeyAnimationDelegate delegateInterface; private bool needsRedraw = false; private bool isReversing; private Hashtable meshObjects; private Hashtable basisMeshes; public Hashtable frames; public Hashtable startShapes; private float shapeKeyStrengthAtTime(ShapeKey shapeKey, float time) { int frameForTime = ((int)Mathf.Floor((time / duration) * (float)(numberOfFrames - 1))); ShapeKeyFrameSequence f = (ShapeKeyFrameSequence)frames[shapeKey]; if (f == null) return 0; if (frameForTime >= numberOfFrames - 1) { return f.strength[numberOfFrames - 1]; } // Get the frame float l = f.strength[frameForTime]; float h = f.strength[frameForTime + 1]; float d = l - h; float lt = (float)frameForTime * frameDelay; float ht = ((float)frameForTime + 1.0f) * frameDelay; float dt = lt - ht; float s = (time - lt) / dt; float r = l + (d * s); /*if (r < 0) r = 0; if (r > 1) r = 1; */ return r; } public void Play() { if (animationState == AnimationState.stopped) { _startTime = Time.timeSinceLevelLoad; _currentTime = _startTime; _endTime = _startTime + duration; animationState = AnimationState.playing; Reset(); } else if (animationState == AnimationState.paused) { float r = _endTime - _currentTime; _endTime = Time.timeSinceLevelLoad + r; _currentTime = Time.timeSinceLevelLoad; animationState = AnimationState.playing; } } private void accumulate() { foreach (DictionaryEntry de in meshObjects) { GameObject meshObject = (GameObject)de.Key; List<ShapeKey> s = (List<ShapeKey>)de.Value; // Get the basis mesh Vector3[] mesh = (Vector3[])((VertexContainer) basisMeshes[meshObject]).vertices.Clone(); for (int i = 0; i < s.Count; i++) { ShapeKey shapeKey = s[i]; shapeKey.strength = shapeKeyStrengthAtTime(shapeKey, currentTime); mesh = shapeKey.applyShapeToVertices(mesh); } Mesh m; if (meshObject.GetComponent("SkinnedMeshRenderer") == null) { MeshFilter f = (MeshFilter) meshObject.GetComponent("MeshFilter"); m = f.mesh; } else { MeshFilter f = (MeshFilter) meshObject.GetComponent("SkinnedMeshRenderer"); m = f.sharedMesh; } m.vertices = mesh; } } public void Pause() { animationState = AnimationState.paused; } public void Stop() { animationState = AnimationState.stopped; } // *ALWAYS* returns the states of the shape keys to FRAME ZERO // This may, if any of the shape keys are applied result in a deformed // mesh, a backup should always be retained. public void Reset() { foreach (DictionaryEntry de in meshObjects) { GameObject meshObject = (GameObject)de.Key; List<ShapeKey> s = (List<ShapeKey>)de.Value; // Get the basis mesh Vector3[] mesh = (Vector3[])((VertexContainer) basisMeshes[meshObject]).vertices.Clone(); for (int i = 0; i < s.Count; i++) { ShapeKey shapeKey = s[i]; if (!startShapes.ContainsKey(shapeKey)) continue; shapeKey.strength = (float)startShapes[shapeKey]; mesh = shapeKey.applyShapeToVertices(mesh); } Mesh m; if (meshObject.GetComponent("SkinnedMeshRenderer") == null) { MeshFilter f = (MeshFilter) meshObject.GetComponent("MeshFilter"); m = f.mesh; } else { MeshFilter f = (MeshFilter) meshObject.GetComponent("SkinnedMeshRenderer"); m = f.sharedMesh; } m.vertices = mesh; } } public void Start() { meshObjects = new Hashtable (); basisMeshes = new Hashtable (); for (int i = 0; i < shapeKeys.shapeKeys.Length; i++) { // Lookup the mesh and collect the list of shape keys for each mesh // Also grab a copy of the basis mesh so we always apply values // against the basis. GameObject meshObject = ((ShapeKey)shapeKeys.shapeKeys[i]).meshObject; if (!meshObjects.Contains(meshObject)) { List<ShapeKey> s = new List<ShapeKey>(); s.Add(shapeKeys.shapeKeys[i]); VertexContainer verts = new VertexContainer(); verts.vertices = (Vector3[])((ShapeKey)shapeKeys.shapeKeys[i]).getVertices().Clone(); meshObjects.Add(meshObject, s); basisMeshes.Add(meshObject, verts); } else { ((List<ShapeKey>)meshObjects[meshObject]).Add(shapeKeys.shapeKeys[i]); } } } public void Update() { if (animationState == AnimationState.playing || needsRedraw) { if (isReversing) { _currentTime -= Time.deltaTime; } else { _currentTime += Time.deltaTime; } if (_currentTime >= _endTime) { _currentTime = _endTime; // Animation ended, Based on animation style work out what to do next if (animationStyle == AnimationStyle.loop) { _currentTime = 0; } else if (animationStyle == AnimationStyle.pingPong) { isReversing = !isReversing; } else if (animationStyle == AnimationStyle.reset) { Reset(); animationState = AnimationState.stopped; } else if (animationStyle == AnimationStyle.end) { animationState = AnimationState.stopped; } } accumulate(); } } } public interface ShapeKeyAnimationDelegate { void animationEnded(string animationName, GameObject target); void animationPlaying(string animationName, GameObject target); void animationPaused(string animationName, GameObject target); void animationLoop(string animationName, GameObject target); void animationReverse(string animationName, GameObject target); } [RequireComponent (typeof (ShapeKeys))] public class ShapeKeyAnimations : MonoBehaviour { public ShapeKeyAnimation[] shapeKeyAnimations; private Hashtable shapekeyanimationlookup; public ShapeKeyAnimation findAnimationNamed(string name) { return (ShapeKeyAnimation)shapekeyanimationlookup [name]; } public void InitialiseAnimations() { shapekeyanimationlookup = new Hashtable (); for (int i = 0; i < shapeKeyAnimations.Length; i++) { shapekeyanimationlookup.Add (shapeKeyAnimations[i].name, shapeKeyAnimations[i]); shapeKeyAnimations[i].parent = this; shapeKeyAnimations[i].shapeKeys = (ShapeKeys)GetComponent("ShapeKeys"); shapeKeyAnimations[i].Start(); } } public void Update() { for (int i = 0; i < shapeKeyAnimations.Length; i++) { shapeKeyAnimations[i].Update(); } } }
// 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.Immutable; using System.IO; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.PortableExecutable { /// <summary> /// An object used to read PE (Portable Executable) and COFF (Common Object File Format) headers from a stream. /// </summary> public sealed class PEHeaders { private readonly CoffHeader _coffHeader; private readonly PEHeader _peHeader; private readonly ImmutableArray<SectionHeader> _sectionHeaders; private readonly CorHeader _corHeader; private readonly bool _isLoadedImage; private readonly int _metadataStartOffset = -1; private readonly int _metadataSize; private readonly int _coffHeaderStartOffset = -1; private readonly int _corHeaderStartOffset = -1; private readonly int _peHeaderStartOffset = -1; /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image starting at the stream's current position and ending at the end of the stream.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> public PEHeaders(Stream peStream) : this(peStream, 0) { } /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param> /// <param name="size">Size of the PE image.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEHeaders(Stream peStream, int size) : this(peStream, size, isLoadedImage: false) { } /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param> /// <param name="size">Size of the PE image.</param> /// <param name="isLoadedImage">True if the PE image has been loaded into memory by the OS loader.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEHeaders(Stream peStream, int size, bool isLoadedImage) { if (peStream == null) { throw new ArgumentNullException(nameof(peStream)); } if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); } _isLoadedImage = isLoadedImage; int actualSize = StreamExtensions.GetAndValidateSize(peStream, size, nameof(peStream)); var reader = new PEBinaryReader(peStream, actualSize); bool isCoffOnly; SkipDosHeader(ref reader, out isCoffOnly); _coffHeaderStartOffset = reader.CurrentOffset; _coffHeader = new CoffHeader(ref reader); if (!isCoffOnly) { _peHeaderStartOffset = reader.CurrentOffset; _peHeader = new PEHeader(ref reader); } _sectionHeaders = this.ReadSectionHeaders(ref reader); if (!isCoffOnly) { int offset; if (TryCalculateCorHeaderOffset(actualSize, out offset)) { _corHeaderStartOffset = offset; reader.Seek(offset); _corHeader = new CorHeader(ref reader); } } CalculateMetadataLocation(actualSize, out _metadataStartOffset, out _metadataSize); } /// <summary> /// Gets the offset (in bytes) from the start of the PE image to the start of the CLI metadata. /// or -1 if the image does not contain metadata. /// </summary> public int MetadataStartOffset { get { return _metadataStartOffset; } } /// <summary> /// Gets the size of the CLI metadata 0 if the image does not contain metadata.) /// </summary> public int MetadataSize { get { return _metadataSize; } } /// <summary> /// Gets the COFF header of the image. /// </summary> public CoffHeader CoffHeader { get { return _coffHeader; } } /// <summary> /// Gets the byte offset from the start of the PE image to the start of the COFF header. /// </summary> public int CoffHeaderStartOffset { get { return _coffHeaderStartOffset; } } /// <summary> /// Determines if the image is Coff only. /// </summary> public bool IsCoffOnly { get { return _peHeader == null; } } /// <summary> /// Gets the PE header of the image or null if the image is COFF only. /// </summary> public PEHeader PEHeader { get { return _peHeader; } } /// <summary> /// Gets the byte offset from the start of the image to /// </summary> public int PEHeaderStartOffset { get { return _peHeaderStartOffset; } } /// <summary> /// Gets the PE section headers. /// </summary> public ImmutableArray<SectionHeader> SectionHeaders { get { return _sectionHeaders; } } /// <summary> /// Gets the CLI header or null if the image does not have one. /// </summary> public CorHeader CorHeader { get { return _corHeader; } } /// <summary> /// Gets the byte offset from the start of the image to the COR header or -1 if the image does not have one. /// </summary> public int CorHeaderStartOffset { get { return _corHeaderStartOffset; } } /// <summary> /// Determines if the image represents a Windows console application. /// </summary> public bool IsConsoleApplication { get { return _peHeader != null && _peHeader.Subsystem == Subsystem.WindowsCui; } } /// <summary> /// Determines if the image represents a dynamically linked library. /// </summary> public bool IsDll { get { return (_coffHeader.Characteristics & Characteristics.Dll) != 0; } } /// <summary> /// Determines if the image represents an executable. /// </summary> public bool IsExe { get { return (_coffHeader.Characteristics & Characteristics.Dll) == 0; } } private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset) { if (!TryGetDirectoryOffset(_peHeader.CorHeaderTableDirectory, out startOffset, canCrossSectionBoundary: false)) { startOffset = -1; return false; } int length = _peHeader.CorHeaderTableDirectory.Size; if (length < COR20Constants.SizeOfCorHeader) { throw new BadImageFormatException(SR.InvalidCorHeaderSize); } return true; } private void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) { // Look for DOS Signature "MZ" ushort dosSig = reader.ReadUInt16(); if (dosSig != PEFileConstants.DosSignature) { // If image doesn't start with DOS signature, let's assume it is a // COFF (Common Object File Format), aka .OBJ file. // See CLiteWeightStgdbRW::FindObjMetaData in ndp\clr\src\MD\enc\peparse.cpp if (dosSig != 0 || reader.ReadUInt16() != 0xffff) { isCOFFOnly = true; reader.Seek(0); } else { // Might need to handle other formats. Anonymous or LTCG objects, for example. throw new BadImageFormatException(SR.UnknownFileFormat); } } else { isCOFFOnly = false; } if (!isCOFFOnly) { // Skip the DOS Header reader.Seek(PEFileConstants.PESignatureOffsetLocation); int ntHeaderOffset = reader.ReadInt32(); reader.Seek(ntHeaderOffset); // Look for PESignature "PE\0\0" uint ntSignature = reader.ReadUInt32(); if (ntSignature != PEFileConstants.PESignature) { throw new BadImageFormatException(SR.InvalidPESignature); } } } private ImmutableArray<SectionHeader> ReadSectionHeaders(ref PEBinaryReader reader) { int numberOfSections = _coffHeader.NumberOfSections; if (numberOfSections < 0) { throw new BadImageFormatException(SR.InvalidNumberOfSections); } var builder = ImmutableArray.CreateBuilder<SectionHeader>(numberOfSections); for (int i = 0; i < numberOfSections; i++) { builder.Add(new SectionHeader(ref reader)); } return builder.ToImmutable(); } /// <summary> /// Gets the offset (in bytes) from the start of the image to the given directory data. /// </summary> /// <param name="directory">PE directory entry</param> /// <param name="offset">Offset from the start of the image to the given directory data</param> /// <returns>True if the directory data is found, false otherwise.</returns> public bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset) { return TryGetDirectoryOffset(directory, out offset, canCrossSectionBoundary: true); } internal bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset, bool canCrossSectionBoundary) { int sectionIndex = GetContainingSectionIndex(directory.RelativeVirtualAddress); if (sectionIndex < 0) { offset = -1; return false; } int relativeOffset = directory.RelativeVirtualAddress - _sectionHeaders[sectionIndex].VirtualAddress; if (!canCrossSectionBoundary && directory.Size > _sectionHeaders[sectionIndex].VirtualSize - relativeOffset) { throw new BadImageFormatException(SR.SectionTooSmall); } offset = _isLoadedImage ? directory.RelativeVirtualAddress : _sectionHeaders[sectionIndex].PointerToRawData + relativeOffset; return true; } /// <summary> /// Searches sections of the PE image for the one that contains specified Relative Virtual Address. /// </summary> /// <param name="relativeVirtualAddress">Address.</param> /// <returns> /// Index of the section that contains <paramref name="relativeVirtualAddress"/>, /// or -1 if there is none. /// </returns> public int GetContainingSectionIndex(int relativeVirtualAddress) { for (int i = 0; i < _sectionHeaders.Length; i++) { if (_sectionHeaders[i].VirtualAddress <= relativeVirtualAddress && relativeVirtualAddress < _sectionHeaders[i].VirtualAddress + _sectionHeaders[i].VirtualSize) { return i; } } return -1; } internal int IndexOfSection(string name) { for (int i = 0; i < SectionHeaders.Length; i++) { if (SectionHeaders[i].Name.Equals(name, StringComparison.Ordinal)) { return i; } } return -1; } private void CalculateMetadataLocation(long peImageSize, out int start, out int size) { if (IsCoffOnly) { int cormeta = IndexOfSection(".cormeta"); if (cormeta == -1) { start = -1; size = 0; return; } if (_isLoadedImage) { start = SectionHeaders[cormeta].VirtualAddress; size = SectionHeaders[cormeta].VirtualSize; } else { start = SectionHeaders[cormeta].PointerToRawData; size = SectionHeaders[cormeta].SizeOfRawData; } } else if (_corHeader == null) { start = 0; size = 0; return; } else { if (!TryGetDirectoryOffset(_corHeader.MetadataDirectory, out start, canCrossSectionBoundary: false)) { throw new BadImageFormatException(SR.MissingDataDirectory); } size = _corHeader.MetadataDirectory.Size; } if (start < 0 || start >= peImageSize || size <= 0 || start > peImageSize - size) { throw new BadImageFormatException(SR.InvalidMetadataSectionSpan); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading.Tasks { /// <summary> /// Provides a set of static (Shared in Visual Basic) methods for working with specific kinds of /// <see cref="System.Threading.Tasks.Task"/> instances. /// </summary> public static class TaskExtensions { /// <summary> /// Creates a proxy <see cref="System.Threading.Tasks.Task">Task</see> that represents the /// asynchronous operation of a Task{Task}. /// </summary> /// <remarks> /// It is often useful to be able to return a Task from a <see cref="System.Threading.Tasks.Task{TResult}"> /// Task{TResult}</see>, where the inner Task represents work done as part of the outer Task{TResult}. However, /// doing so results in a Task{Task}, which, if not dealt with carefully, could produce unexpected behavior. Unwrap /// solves this problem by creating a proxy Task that represents the entire asynchronous operation of such a Task{Task}. /// </remarks> /// <param name="task">The Task{Task} to unwrap.</param> /// <exception cref="T:System.ArgumentNullException">The exception that is thrown if the /// <paramref name="task"/> argument is null.</exception> /// <returns>A Task that represents the asynchronous operation of the provided Task{Task}.</returns> public static Task Unwrap(this Task<Task> task) { if (task == null) throw new ArgumentNullException(nameof(task)); // Fast path for an already successfully completed outer task: just return the inner one. // As in the subsequent slower path, a null inner task is special-cased to mean cancellation. if (task.Status == TaskStatus.RanToCompletion && (task.CreationOptions & TaskCreationOptions.AttachedToParent) == 0) { return task.Result ?? Task.FromCanceled(new CancellationToken(true)); } // Create a new Task to serve as a proxy for the actual inner task. Attach it // to the parent if the original was attached to the parent. var tcs = new TaskCompletionSource<VoidResult>(task.CreationOptions & TaskCreationOptions.AttachedToParent); TransferAsynchronously(tcs, task); return tcs.Task; } /// <summary> /// Creates a proxy <see cref="System.Threading.Tasks.Task{TResult}">Task{TResult}</see> that represents the /// asynchronous operation of a Task{Task{TResult}}. /// </summary> /// <remarks> /// It is often useful to be able to return a Task{TResult} from a Task{TResult}, where the inner Task{TResult} /// represents work done as part of the outer Task{TResult}. However, doing so results in a Task{Task{TResult}}, /// which, if not dealt with carefully, could produce unexpected behavior. Unwrap solves this problem by /// creating a proxy Task{TResult} that represents the entire asynchronous operation of such a Task{Task{TResult}}. /// </remarks> /// <param name="task">The Task{Task{TResult}} to unwrap.</param> /// <exception cref="T:System.ArgumentNullException">The exception that is thrown if the /// <paramref name="task"/> argument is null.</exception> /// <returns>A Task{TResult} that represents the asynchronous operation of the provided Task{Task{TResult}}.</returns> public static Task<TResult> Unwrap<TResult>(this Task<Task<TResult>> task) { if (task == null) throw new ArgumentNullException(nameof(task)); // Fast path for an already successfully completed outer task: just return the inner one. // As in the subsequent slower path, a null inner task is special-cased to mean cancellation. if (task.Status == TaskStatus.RanToCompletion && (task.CreationOptions & TaskCreationOptions.AttachedToParent) == 0) { return task.Result ?? Task.FromCanceled<TResult>(new CancellationToken(true)); } // Create a new Task to serve as a proxy for the actual inner task. Attach it // to the parent if the original was attached to the parent. var tcs = new TaskCompletionSource<TResult>(task.CreationOptions & TaskCreationOptions.AttachedToParent); TransferAsynchronously(tcs, task); return tcs.Task; } /// <summary> /// Transfer the results of the <paramref name="outer"/> task's inner task to the <paramref name="completionSource"/>. /// </summary> /// <param name="completionSource">The completion source to which results should be transfered.</param> /// <param name="outer"> /// The outer task that when completed will yield an inner task whose results we want marshaled to the <paramref name="completionSource"/>. /// </param> private static void TransferAsynchronously<TResult, TInner>(TaskCompletionSource<TResult> completionSource, Task<TInner> outer) where TInner : Task { Action callback = null; // Create a continuation delegate. For performance reasons, we reuse the same delegate/closure across multiple // continuations; by using .ConfigureAwait(false).GetAwaiter().UnsafeOnComplete(action), in most cases // this delegate can be stored directly into the Task's continuation field, eliminating the need for additional // allocations. Thus, this whole Unwrap operation generally results in four allocations: one for the TaskCompletionSource, // one for the returned task, one for the delegate, and one for the closure. Since the delegate is used // across multiple continuations, we use the callback variable as well to indicate which continuation we're in: // if the callback is non-null, then we're processing the continuation for the outer task and use the callback // object as the continuation off of the inner task; if the callback is null, then we're processing the // inner task. callback = delegate { Debug.Assert(outer.IsCompleted); if (callback != null) { // Process the outer task's completion // Clear out the callback field to indicate that any future invocations should // be for processing the inner task, but store away a local copy in case we need // to use it as the continuation off of the outer task. Action innerCallback = callback; callback = null; bool result = true; switch (outer.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: // The outer task has completed as canceled or faulted; transfer that // status to the completion source, and we're done. result = completionSource.TrySetFromTask(outer); break; case TaskStatus.RanToCompletion: Task inner = outer.Result; if (inner == null) { // The outer task completed successfully, but with a null inner task; // cancel the completionSource, and we're done. result = completionSource.TrySetCanceled(); } else if (inner.IsCompleted) { // The inner task also completed! Transfer the results, and we're done. result = completionSource.TrySetFromTask(inner); } else { // Run this delegate again once the inner task has completed. inner.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(innerCallback); } break; } Debug.Assert(result); } else { // Process the inner task's completion. All we need to do is transfer its results // to the completion source. Debug.Assert(outer.Status == TaskStatus.RanToCompletion); Debug.Assert(outer.Result.IsCompleted); completionSource.TrySetFromTask(outer.Result); } }; // Kick things off by hooking up the callback as the task's continuation outer.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(callback); } /// <summary>Copies that ending state information from <paramref name="task"/> to <paramref name="completionSource"/>.</summary> private static bool TrySetFromTask<TResult>(this TaskCompletionSource<TResult> completionSource, Task task) { Debug.Assert(task.IsCompleted); // Before transferring the results, check to make sure we're not too deep on the stack. Calling TrySet* // will cause any synchronous continuations to be invoked, which is fine unless we're so deep that doing // so overflows. ContinueWith has built-in support for avoiding such stack dives, but that support is not // (yet) part of await's infrastructure, so until it is we mimic it manually. This matches the behavior // employed by the Unwrap implementation in mscorlib. (If TryEnsureSufficientExecutionStack is made public // in the future, switch to using it to avoid the try/catch block and exception.) try { RuntimeHelpers.EnsureSufficientExecutionStack(); } catch (InsufficientExecutionStackException) { // This is very rare. We're too deep to safely invoke // TrySet* synchronously, so do so asynchronously instead. Task.Factory.StartNew(s => { var t = (Tuple<TaskCompletionSource<TResult>, Task>)s; TrySetFromTask(t.Item1, t.Item2); }, Tuple.Create(completionSource, task), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return true; } // Transfer the results from the supplied Task to the TaskCompletionSource. bool result = false; switch(task.Status) { case TaskStatus.Canceled: result = completionSource.TrySetCanceled(ExtractCancellationToken(task)); break; case TaskStatus.Faulted: result = completionSource.TrySetException(task.Exception.InnerExceptions); break; case TaskStatus.RanToCompletion: Task<TResult> resultTask = task as Task<TResult>; result = resultTask != null ? completionSource.TrySetResult(resultTask.Result) : completionSource.TrySetResult(default(TResult)); break; } return result; } /// <summary>Gets the CancellationToken associated with a canceled task.</summary> private static CancellationToken ExtractCancellationToken(Task task) { // With the public Task APIs as of .NET 4.6, the only way to extract a CancellationToken // that was associated with a Task is by await'ing it, catching the resulting // OperationCanceledException, and getting the token from the OCE. Debug.Assert(task.IsCanceled); try { task.GetAwaiter().GetResult(); Debug.Fail("Waiting on the canceled task should always result in an OCE, even if it's manufactured at the time of the wait."); return new CancellationToken(true); } catch (OperationCanceledException oce) { // This token may not have cancellation requested; that's ok. // That can happen if, for example, the Task is canceled with // TaskCompletionSource<T>.SetCanceled(), without a token. return oce.CancellationToken; } } /// <summary>Dummy type to use as a void TResult.</summary> private struct VoidResult { } } }
//--------------------------------------------------------------------- // <copyright file="ExpressionPrinter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Common.CommandTrees.Internal { using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Common.CommandTrees; using System.Data.Common.Utils; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; /// <summary> /// Prints a command tree /// </summary> internal class ExpressionPrinter : TreePrinter { private PrinterVisitor _visitor = new PrinterVisitor(); internal ExpressionPrinter() : base() {} [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal string Print(DbExpression expr) { Debug.Assert(expr != null, "Null DbExpression"); return this.Print(_visitor.VisitExpression(expr)); } internal string Print(DbDeleteCommandTree tree) { // Predicate should not be null since DbDeleteCommandTree initializes it to DbConstantExpression(true) Debug.Assert(tree != null && tree.Predicate != null, "Invalid DbDeleteCommandTree"); TreeNode targetNode; if (tree.Target != null) { targetNode = _visitor.VisitBinding("Target", tree.Target); } else { targetNode = new TreeNode("Target"); } TreeNode predicateNode; if (tree.Predicate != null) { predicateNode = _visitor.VisitExpression("Predicate", tree.Predicate); } else { predicateNode = new TreeNode("Predicate"); } return this.Print(new TreeNode( "DbDeleteCommandTree", CreateParametersNode(tree), targetNode, predicateNode)); } internal string Print(DbFunctionCommandTree tree) { Debug.Assert(tree != null, "Null DbFunctionCommandTree"); TreeNode funcNode = new TreeNode("EdmFunction"); if (tree.EdmFunction != null) { funcNode.Children.Add(_visitor.VisitFunction(tree.EdmFunction, null)); } TreeNode typeNode = new TreeNode("ResultType"); if (tree.ResultType != null) { PrinterVisitor.AppendTypeSpecifier(typeNode, tree.ResultType); } return this.Print(new TreeNode("DbFunctionCommandTree", CreateParametersNode(tree), funcNode, typeNode)); } internal string Print(DbInsertCommandTree tree) { Debug.Assert(tree != null, "Null DbInsertCommandTree"); TreeNode targetNode = null; if (tree.Target != null) { targetNode = _visitor.VisitBinding("Target", tree.Target); } else { targetNode = new TreeNode("Target"); } TreeNode clausesNode = new TreeNode("SetClauses"); foreach (DbModificationClause clause in tree.SetClauses) { if (clause != null) { clausesNode.Children.Add(clause.Print(_visitor)); } } TreeNode returningNode = null; if (null != tree.Returning) { returningNode = new TreeNode("Returning", _visitor.VisitExpression(tree.Returning)); } else { returningNode = new TreeNode("Returning"); } return this.Print(new TreeNode( "DbInsertCommandTree", CreateParametersNode(tree), targetNode, clausesNode, returningNode)); } internal string Print(DbUpdateCommandTree tree) { // Predicate should not be null since DbUpdateCommandTree initializes it to DbConstantExpression(true) Debug.Assert(tree != null && tree.Predicate != null, "Invalid DbUpdateCommandTree"); TreeNode targetNode = null; if (tree.Target != null) { targetNode = _visitor.VisitBinding("Target", tree.Target); } else { targetNode = new TreeNode("Target"); } TreeNode clausesNode = new TreeNode("SetClauses"); foreach (DbModificationClause clause in tree.SetClauses) { if (clause != null) { clausesNode.Children.Add(clause.Print(_visitor)); } } TreeNode predicateNode; if (null != tree.Predicate) { predicateNode = new TreeNode("Predicate", _visitor.VisitExpression(tree.Predicate)); } else { predicateNode = new TreeNode("Predicate"); } TreeNode returningNode; if (null != tree.Returning) { returningNode = new TreeNode("Returning", _visitor.VisitExpression(tree.Returning)); } else { returningNode = new TreeNode("Returning"); } return this.Print(new TreeNode( "DbUpdateCommandTree", CreateParametersNode(tree), targetNode, clausesNode, predicateNode, returningNode)); } internal string Print(DbQueryCommandTree tree) { Debug.Assert(tree != null, "Null DbQueryCommandTree"); TreeNode queryNode = new TreeNode("Query"); if (tree.Query != null) { PrinterVisitor.AppendTypeSpecifier(queryNode, tree.Query.ResultType); queryNode.Children.Add(_visitor.VisitExpression(tree.Query)); } return this.Print(new TreeNode("DbQueryCommandTree", CreateParametersNode(tree), queryNode)); } private static TreeNode CreateParametersNode(DbCommandTree tree) { TreeNode retNode = new TreeNode("Parameters"); foreach (KeyValuePair<string, TypeUsage> paramInfo in tree.Parameters) { TreeNode paramNode = new TreeNode(paramInfo.Key); PrinterVisitor.AppendTypeSpecifier(paramNode, paramInfo.Value); retNode.Children.Add(paramNode); } return retNode; } private class PrinterVisitor : DbExpressionVisitor<TreeNode> { private static Dictionary<DbExpressionKind, string> _opMap = InitializeOpMap(); private static Dictionary<DbExpressionKind, string> InitializeOpMap() { Dictionary<DbExpressionKind, string> opMap = new Dictionary<DbExpressionKind, string>(12); // Arithmetic opMap[DbExpressionKind.Divide] = "/"; opMap[DbExpressionKind.Modulo] = "%"; opMap[DbExpressionKind.Multiply] = "*"; opMap[DbExpressionKind.Plus] = "+"; opMap[DbExpressionKind.Minus] = "-"; opMap[DbExpressionKind.UnaryMinus] = "-"; // Comparison opMap[DbExpressionKind.Equals] = "="; opMap[DbExpressionKind.LessThan] = "<"; opMap[DbExpressionKind.LessThanOrEquals] = "<="; opMap[DbExpressionKind.GreaterThan] = ">"; opMap[DbExpressionKind.GreaterThanOrEquals] = ">="; opMap[DbExpressionKind.NotEquals] = "<>"; return opMap; } private int _maxStringLength = 80; private bool _infix = true; internal TreeNode VisitExpression(DbExpression expr) { return expr.Accept<TreeNode>(this); } internal TreeNode VisitExpression(string name, DbExpression expr) { return new TreeNode(name, expr.Accept<TreeNode>(this)); } internal TreeNode VisitBinding(string propName, DbExpressionBinding binding) { return this.VisitWithLabel(propName, binding.VariableName, binding.Expression); } internal TreeNode VisitFunction(EdmFunction func, IList<DbExpression> args) { TreeNode funcInfo = new TreeNode(); AppendFullName(funcInfo.Text, func); AppendParameters(funcInfo, func.Parameters.Select(fp => new KeyValuePair<string, TypeUsage>(fp.Name, fp.TypeUsage))); if (args != null) { AppendArguments(funcInfo, func.Parameters.Select(fp => fp.Name).ToArray(), args); } return funcInfo; } private static TreeNode NodeFromExpression(DbExpression expr) { return new TreeNode(Enum.GetName(typeof(DbExpressionKind), expr.ExpressionKind)); } private static void AppendParameters(TreeNode node, IEnumerable<KeyValuePair<string, TypeUsage>> paramInfos) { node.Text.Append("("); int pos = 0; foreach(KeyValuePair<string, TypeUsage> paramInfo in paramInfos) { if (pos > 0) { node.Text.Append(", "); } AppendType(node, paramInfo.Value); node.Text.Append(" "); node.Text.Append(paramInfo.Key); pos++; } node.Text.Append(")"); } internal static void AppendTypeSpecifier(TreeNode node, TypeUsage type) { node.Text.Append(" : "); AppendType(node, type); } internal static void AppendType(TreeNode node, TypeUsage type) { BuildTypeName(node.Text, type); } private static void BuildTypeName(StringBuilder text, TypeUsage type) { RowType rowType = type.EdmType as RowType; CollectionType collType = type.EdmType as CollectionType; RefType refType = type.EdmType as RefType; if (TypeSemantics.IsPrimitiveType(type)) { text.Append(type); } else if (collType != null) { text.Append("Collection{"); BuildTypeName(text, collType.TypeUsage); text.Append("}"); } else if (refType != null) { text.Append("Ref<"); AppendFullName(text, refType.ElementType); text.Append(">"); } else if (rowType != null) { text.Append("Record["); int idx = 0; foreach (EdmProperty recColumn in rowType.Properties) { text.Append("'"); text.Append(recColumn.Name); text.Append("'"); text.Append("="); BuildTypeName(text, recColumn.TypeUsage); idx++; if (idx < rowType.Properties.Count) { text.Append(", "); } } text.Append("]"); } else { // Entity, Relationship, Complex if (!string.IsNullOrEmpty(type.EdmType.NamespaceName)) { text.Append(type.EdmType.NamespaceName); text.Append("."); } text.Append(type.EdmType.Name); } } private static void AppendFullName(StringBuilder text, EdmType type) { if (BuiltInTypeKind.RowType != type.BuiltInTypeKind) { if (!string.IsNullOrEmpty(type.NamespaceName)) { text.Append(type.NamespaceName); text.Append("."); } } text.Append(type.Name); } private List<TreeNode> VisitParams(IList<string> paramInfo, IList<DbExpression> args) { List<TreeNode> retInfo = new List<TreeNode>(); for (int idx = 0; idx < paramInfo.Count; idx++) { TreeNode paramNode = new TreeNode(paramInfo[idx]); paramNode.Children.Add(this.VisitExpression(args[idx])); retInfo.Add(paramNode); } return retInfo; } private void AppendArguments(TreeNode node, IList<string> paramNames, IList<DbExpression> args) { if (paramNames.Count > 0) { node.Children.Add(new TreeNode("Arguments", VisitParams(paramNames, args))); } } private TreeNode VisitWithLabel(string label, string name, DbExpression def) { TreeNode retInfo = new TreeNode(label); retInfo.Text.Append(" : '"); retInfo.Text.Append(name); retInfo.Text.Append("'"); retInfo.Children.Add(this.VisitExpression(def)); return retInfo; } private TreeNode VisitBindingList(string propName, IList<DbExpressionBinding> bindings) { List<TreeNode> bindingInfos = new List<TreeNode>(); for (int idx = 0; idx < bindings.Count; idx++) { bindingInfos.Add(this.VisitBinding(StringUtil.FormatIndex(propName, idx), bindings[idx])); } return new TreeNode(propName, bindingInfos); } private TreeNode VisitGroupBinding(DbGroupExpressionBinding groupBinding) { TreeNode inputInfo = this.VisitExpression(groupBinding.Expression); TreeNode retInfo = new TreeNode(); retInfo.Children.Add(inputInfo); retInfo.Text.AppendFormat(CultureInfo.InvariantCulture, "Input : '{0}', '{1}'", groupBinding.VariableName, groupBinding.GroupVariableName); return retInfo; } private TreeNode Visit(string name, params DbExpression[] exprs) { TreeNode retInfo = new TreeNode(name); foreach (DbExpression expr in exprs) { retInfo.Children.Add(this.VisitExpression(expr)); } return retInfo; } private TreeNode VisitInfix(DbExpression root, DbExpression left, string name, DbExpression right) { if (_infix) { TreeNode nullOp = new TreeNode(""); nullOp.Children.Add(this.VisitExpression(left)); nullOp.Children.Add(new TreeNode(name)); nullOp.Children.Add(this.VisitExpression(right)); return nullOp; } else { return Visit(name, left, right); } } private TreeNode VisitUnary(DbUnaryExpression expr) { return VisitUnary(expr, false); } private TreeNode VisitUnary(DbUnaryExpression expr, bool appendType) { TreeNode retInfo = NodeFromExpression(expr); if (appendType) { AppendTypeSpecifier(retInfo, expr.ResultType); } retInfo.Children.Add(this.VisitExpression(expr.Argument)); return retInfo; } private TreeNode VisitBinary(DbBinaryExpression expr) { TreeNode retInfo = NodeFromExpression(expr); retInfo.Children.Add(this.VisitExpression(expr.Left)); retInfo.Children.Add(this.VisitExpression(expr.Right)); return retInfo; } #region DbExpressionVisitor<DbExpression> Members public override TreeNode Visit(DbExpression e) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.Cqt_General_UnsupportedExpression(e.GetType().FullName)); } public override TreeNode Visit(DbConstantExpression e) { TreeNode retInfo = new TreeNode(); string stringVal = e.Value as string; if (stringVal != null) { stringVal = stringVal.Replace("\r\n", "\\r\\n"); int appendLength = stringVal.Length; if (_maxStringLength > 0) { appendLength = Math.Min(stringVal.Length, _maxStringLength); } retInfo.Text.Append("'"); retInfo.Text.Append(stringVal, 0, appendLength); if (stringVal.Length > appendLength) { retInfo.Text.Append("..."); } retInfo.Text.Append("'"); } else { retInfo.Text.Append(e.Value.ToString()); } return retInfo; } public override TreeNode Visit(DbNullExpression e) { return new TreeNode("null"); } public override TreeNode Visit(DbVariableReferenceExpression e) { TreeNode retInfo = new TreeNode(); retInfo.Text.AppendFormat("Var({0})", e.VariableName); return retInfo; } public override TreeNode Visit(DbParameterReferenceExpression e) { TreeNode retInfo = new TreeNode(); retInfo.Text.AppendFormat("@{0}", e.ParameterName); return retInfo; } public override TreeNode Visit(DbFunctionExpression e) { TreeNode funcInfo = VisitFunction(e.Function, e.Arguments); return funcInfo; } public override TreeNode Visit(DbLambdaExpression expression) { TreeNode lambdaInfo = new TreeNode(); lambdaInfo.Text.Append("Lambda"); AppendParameters(lambdaInfo, expression.Lambda.Variables.Select(v => new KeyValuePair<string, TypeUsage>(v.VariableName, v.ResultType))); AppendArguments(lambdaInfo, expression.Lambda.Variables.Select(v => v.VariableName).ToArray(), expression.Arguments); lambdaInfo.Children.Add(this.Visit("Body", expression.Lambda.Body)); return lambdaInfo; } #if METHOD_EXPRESSION public override TreeNode Visit(MethodExpression e) { TreeNode retInfo = null; retInfo = new TreeNode("."); AppendType(retInfo, e.Method.DefiningType); retInfo.Text.Append("."); retInfo.Text.Append(e.Method.Name); AppendParameters(retInfo, e.Method.Parameters); if (e.Instance != null) { retInfo.Children.Add(this.Visit("Instance", e.Instance)); } AppendArguments(retInfo, e.Method.Parameters, e.Arguments); return retInfo; } #endif public override TreeNode Visit(DbPropertyExpression e) { TreeNode inst = null; if (e.Instance != null) { inst = this.VisitExpression(e.Instance); if (e.Instance.ExpressionKind == DbExpressionKind.VariableReference || (e.Instance.ExpressionKind == DbExpressionKind.Property && 0 == inst.Children.Count)) { inst.Text.Append("."); inst.Text.Append(e.Property.Name); return inst; } } TreeNode retInfo = new TreeNode("."); EdmProperty prop = e.Property as EdmProperty; if (prop != null && !(prop.DeclaringType is RowType)) { // Entity, Relationship, Complex AppendFullName(retInfo.Text, prop.DeclaringType); retInfo.Text.Append("."); } retInfo.Text.Append(e.Property.Name); if (inst != null) { retInfo.Children.Add(new TreeNode("Instance", inst)); } return retInfo; } public override TreeNode Visit(DbComparisonExpression e) { return this.VisitInfix(e, e.Left, _opMap[e.ExpressionKind], e.Right); } public override TreeNode Visit(DbLikeExpression e) { return this.Visit("Like", e.Argument, e.Pattern, e.Escape); } public override TreeNode Visit(DbLimitExpression e) { return this.Visit((e.WithTies ? "LimitWithTies" : "Limit"), e.Argument, e.Limit); } public override TreeNode Visit(DbIsNullExpression e) { return this.VisitUnary(e); } public override TreeNode Visit(DbArithmeticExpression e) { if (DbExpressionKind.UnaryMinus == e.ExpressionKind) { return this.Visit(_opMap[e.ExpressionKind], e.Arguments[0]); } else { return this.VisitInfix(e, e.Arguments[0], _opMap[e.ExpressionKind], e.Arguments[1]); } } public override TreeNode Visit(DbAndExpression e) { return this.VisitInfix(e, e.Left, "And", e.Right); } public override TreeNode Visit(DbOrExpression e) { return this.VisitInfix(e, e.Left, "Or", e.Right); } public override TreeNode Visit(DbNotExpression e) { return this.VisitUnary(e); } public override TreeNode Visit(DbDistinctExpression e) { return this.VisitUnary(e); } public override TreeNode Visit(DbElementExpression e) { return this.VisitUnary(e, true); } public override TreeNode Visit(DbIsEmptyExpression e) { return this.VisitUnary(e); } public override TreeNode Visit(DbUnionAllExpression e) { return this.VisitBinary(e); } public override TreeNode Visit(DbIntersectExpression e) { return this.VisitBinary(e); } public override TreeNode Visit(DbExceptExpression e) { return this.VisitBinary(e); } private TreeNode VisitCastOrTreat(string op, DbUnaryExpression e) { TreeNode retInfo = null; TreeNode argInfo = this.VisitExpression(e.Argument); if (0 == argInfo.Children.Count) { argInfo.Text.Insert(0, op); argInfo.Text.Insert(op.Length, '('); argInfo.Text.Append(" As "); AppendType(argInfo, e.ResultType); argInfo.Text.Append(")"); retInfo = argInfo; } else { retInfo = new TreeNode(op); AppendTypeSpecifier(retInfo, e.ResultType); retInfo.Children.Add(argInfo); } return retInfo; } public override TreeNode Visit(DbTreatExpression e) { return VisitCastOrTreat("Treat", e); } public override TreeNode Visit(DbCastExpression e) { return VisitCastOrTreat("Cast", e); } public override TreeNode Visit(DbIsOfExpression e) { TreeNode retInfo = new TreeNode(); if (DbExpressionKind.IsOfOnly == e.ExpressionKind) { retInfo.Text.Append("IsOfOnly"); } else { retInfo.Text.Append("IsOf"); } AppendTypeSpecifier(retInfo, e.OfType); retInfo.Children.Add(this.VisitExpression(e.Argument)); return retInfo; } public override TreeNode Visit(DbOfTypeExpression e) { TreeNode retInfo = new TreeNode(e.ExpressionKind == DbExpressionKind.OfTypeOnly ? "OfTypeOnly" : "OfType"); AppendTypeSpecifier(retInfo, e.OfType); retInfo.Children.Add(this.VisitExpression(e.Argument)); return retInfo; } public override TreeNode Visit(DbCaseExpression e) { TreeNode retInfo = new TreeNode("Case"); for (int idx = 0; idx < e.When.Count; idx++) { retInfo.Children.Add(this.Visit("When", e.When[idx])); retInfo.Children.Add(this.Visit("Then", e.Then[idx])); } retInfo.Children.Add(this.Visit("Else", e.Else)); return retInfo; } public override TreeNode Visit(DbNewInstanceExpression e) { TreeNode retInfo = NodeFromExpression(e); AppendTypeSpecifier(retInfo, e.ResultType); if (BuiltInTypeKind.CollectionType == e.ResultType.EdmType.BuiltInTypeKind) { foreach (DbExpression element in e.Arguments) { retInfo.Children.Add(this.VisitExpression(element)); } } else { string description = (BuiltInTypeKind.RowType == e.ResultType.EdmType.BuiltInTypeKind) ? "Column" : "Property"; IList<EdmProperty> properties = TypeHelpers.GetProperties(e.ResultType); for (int idx = 0; idx < properties.Count; idx++) { retInfo.Children.Add(this.VisitWithLabel(description, properties[idx].Name, e.Arguments[idx])); } if (BuiltInTypeKind.EntityType == e.ResultType.EdmType.BuiltInTypeKind && e.HasRelatedEntityReferences) { TreeNode references = new TreeNode("RelatedEntityReferences"); foreach (DbRelatedEntityRef relatedRef in e.RelatedEntityReferences) { TreeNode refNode = CreateNavigationNode(relatedRef.SourceEnd, relatedRef.TargetEnd); refNode.Children.Add(CreateRelationshipNode((RelationshipType)relatedRef.SourceEnd.DeclaringType)); refNode.Children.Add(VisitExpression(relatedRef.TargetEntityReference)); references.Children.Add(refNode); } retInfo.Children.Add(references); } } return retInfo; } public override TreeNode Visit(DbRefExpression e) { TreeNode retNode = new TreeNode("Ref"); retNode.Text.Append("<"); AppendFullName(retNode.Text, TypeHelpers.GetEdmType<RefType>(e.ResultType).ElementType); retNode.Text.Append(">"); TreeNode setNode = new TreeNode("EntitySet : "); setNode.Text.Append(e.EntitySet.EntityContainer.Name); setNode.Text.Append("."); setNode.Text.Append(e.EntitySet.Name); retNode.Children.Add(setNode); retNode.Children.Add(this.Visit("Keys", e.Argument)); return retNode; } private TreeNode CreateRelationshipNode(RelationshipType relType) { TreeNode rel = new TreeNode("Relationship"); rel.Text.Append(" : "); AppendFullName(rel.Text, relType); return rel; } private TreeNode CreateNavigationNode(RelationshipEndMember fromEnd, RelationshipEndMember toEnd) { TreeNode nav = new TreeNode(); nav.Text.Append("Navigation : "); nav.Text.Append(fromEnd.Name); nav.Text.Append(" -> "); nav.Text.Append(toEnd.Name); return nav; } public override TreeNode Visit(DbRelationshipNavigationExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(CreateRelationshipNode(e.Relationship)); retInfo.Children.Add(CreateNavigationNode(e.NavigateFrom, e.NavigateTo)); retInfo.Children.Add(this.Visit("Source", e.NavigationSource)); return retInfo; } public override TreeNode Visit(DbDerefExpression e) { return this.VisitUnary(e); } public override TreeNode Visit(DbRefKeyExpression e) { return this.VisitUnary(e, true); } public override TreeNode Visit(DbEntityRefExpression e) { return this.VisitUnary(e, true); } public override TreeNode Visit(DbScanExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Text.Append(" : "); retInfo.Text.Append(e.Target.EntityContainer.Name); retInfo.Text.Append("."); retInfo.Text.Append(e.Target.Name); return retInfo; } public override TreeNode Visit(DbFilterExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitBinding("Input", e.Input)); retInfo.Children.Add(this.Visit("Predicate", e.Predicate)); return retInfo; } public override TreeNode Visit(DbProjectExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitBinding("Input", e.Input)); retInfo.Children.Add(this.Visit("Projection", e.Projection)); return retInfo; } public override TreeNode Visit(DbCrossJoinExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitBindingList("Inputs", e.Inputs)); return retInfo; } public override TreeNode Visit(DbJoinExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitBinding("Left", e.Left)); retInfo.Children.Add(this.VisitBinding("Right", e.Right)); retInfo.Children.Add(this.Visit("JoinCondition", e.JoinCondition)); return retInfo; } public override TreeNode Visit(DbApplyExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitBinding("Input", e.Input)); retInfo.Children.Add(this.VisitBinding("Apply", e.Apply)); return retInfo; } public override TreeNode Visit(DbGroupByExpression e) { List<TreeNode> keys = new List<TreeNode>(); List<TreeNode> aggs = new List<TreeNode>(); RowType outputType = TypeHelpers.GetEdmType<RowType>(TypeHelpers.GetEdmType<CollectionType>(e.ResultType).TypeUsage); int keyIdx = 0; for (int idx = 0; idx < e.Keys.Count; idx++) { keys.Add(this.VisitWithLabel("Key", outputType.Properties[idx].Name, e.Keys[keyIdx])); keyIdx++; } int aggIdx = 0; for (int idx = e.Keys.Count; idx < outputType.Properties.Count; idx++) { TreeNode aggInfo = new TreeNode("Aggregate : '"); aggInfo.Text.Append(outputType.Properties[idx].Name); aggInfo.Text.Append("'"); DbFunctionAggregate funcAgg = e.Aggregates[aggIdx] as DbFunctionAggregate; if (funcAgg != null) { TreeNode funcInfo = this.VisitFunction(funcAgg.Function, funcAgg.Arguments); if (funcAgg.Distinct) { funcInfo = new TreeNode("Distinct", funcInfo); } aggInfo.Children.Add(funcInfo); } else { DbGroupAggregate groupAgg = e.Aggregates[aggIdx] as DbGroupAggregate; Debug.Assert(groupAgg != null, "Invalid DbAggregate"); aggInfo.Children.Add(this.Visit("GroupAggregate", groupAgg.Arguments[0])); } aggs.Add(aggInfo); aggIdx++; } TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitGroupBinding(e.Input)); if (keys.Count > 0) { retInfo.Children.Add(new TreeNode("Keys", keys)); } if (aggs.Count > 0) { retInfo.Children.Add(new TreeNode("Aggregates", aggs)); } return retInfo; } private TreeNode VisitSortOrder(IList<DbSortClause> sortOrder) { TreeNode keyInfo = new TreeNode("SortOrder"); foreach (DbSortClause clause in sortOrder) { TreeNode key = this.Visit((clause.Ascending ? "Asc" : "Desc"), clause.Expression); if (!string.IsNullOrEmpty(clause.Collation)) { key.Text.Append(" : "); key.Text.Append(clause.Collation); } keyInfo.Children.Add(key); } return keyInfo; } public override TreeNode Visit(DbSkipExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitBinding("Input", e.Input)); retInfo.Children.Add(this.VisitSortOrder(e.SortOrder)); retInfo.Children.Add(this.Visit("Count", e.Count)); return retInfo; } public override TreeNode Visit(DbSortExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitBinding("Input", e.Input)); retInfo.Children.Add(this.VisitSortOrder(e.SortOrder)); return retInfo; } public override TreeNode Visit(DbQuantifierExpression e) { TreeNode retInfo = NodeFromExpression(e); retInfo.Children.Add(this.VisitBinding("Input", e.Input)); retInfo.Children.Add(this.Visit("Predicate", e.Predicate)); return retInfo; } #endregion } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Xunit; using Shouldly; using System.Linq; using System.Dynamic; using System.Linq.Expressions; namespace AutoMapper.UnitTests.ArraysAndLists { public class When_mapping_to_an_array_as_ICollection_with_MapAtRuntime : AutoMapperSpecBase { Destination _destination; SourceItem[] _sourceItems = new [] { new SourceItem { Value = "1" }, new SourceItem { Value = "2" }, new SourceItem { Value = "3" } }; public class Source { public ICollection<SourceItem> Items { get; set; } } public class Destination { public ICollection<DestinationItem> Items { get; set; } } public class SourceItem { public string Value { get; set; } } public class DestinationItem { public string Value { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(c => { c.CreateMap<Source, Destination>().ForMember(d=>d.Items, o=>o.MapAtRuntime()); c.CreateMap<SourceItem, DestinationItem>(); }); protected override void Because_of() { var source = new Source { Items = _sourceItems }; _destination = Mapper.Map(source, new Destination { Items = new[] { new DestinationItem { Value = "4" } } }); } [Fact] public void Should_map_ok() { _destination.Items.Select(i => i.Value).SequenceEqual(_sourceItems.Select(i => i.Value)).ShouldBeTrue(); } } public class When_mapping_an_array : AutoMapperSpecBase { decimal[] _source = Enumerable.Range(1, 10).Select(i=>(decimal)i).ToArray(); decimal[] _destination; protected override MapperConfiguration Configuration => new MapperConfiguration(c =>{}); protected override void Because_of() { _destination = Mapper.Map<decimal[]>(_source); } [Fact] public void Should_return_a_copy() { _destination.ShouldNotBeSameAs(_source); } } public class When_mapping_a_primitive_array : AutoMapperSpecBase { int[] _source = Enumerable.Range(1, 10).ToArray(); long[] _destination; protected override MapperConfiguration Configuration => new MapperConfiguration(c =>{}); protected override void Because_of() { _destination = Mapper.Map<long[]>(_source); } [Fact] public void Should_return_a_copy() { var source = new int[] {1, 2, 3, 4}; var dest = new long[4]; Array.Copy(source, dest, 4); dest[3].ShouldBe(4L); var plan = Configuration.BuildExecutionPlan(typeof(int[]), typeof(long[])); _destination.ShouldNotBeSameAs(_source); } } public class When_mapping_a_primitive_array_with_custom_mapping_function : AutoMapperSpecBase { int[] _source = Enumerable.Range(1, 10).ToArray(); int[] _destination; protected override MapperConfiguration Configuration => new MapperConfiguration(c => c.CreateMap<int, int>().ConstructUsing(i => i * 1000)); protected override void Because_of() { _destination = Mapper.Map<int[]>(_source); } [Fact] public void Should_map_each_item() { for (var i = 0; i < _source.Length; i++) { _destination[i].ShouldBe((i+1) * 1000); } } } public class When_mapping_a_primitive_array_with_custom_object_mapper : AutoMapperSpecBase { int[] _source = Enumerable.Range(1, 10).ToArray(); int[] _destination; private class IntToIntMapper : IObjectMapper { public bool IsMatch(TypePair context) => context.SourceType == typeof(int) && context.DestinationType == typeof(int); public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, IMemberMap memberMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) => Expression.Multiply(Expression.Convert(sourceExpression, typeof(int)), Expression.Constant(1000)); } protected override MapperConfiguration Configuration => new MapperConfiguration(c => c.Mappers.Insert(0, new IntToIntMapper())); protected override void Because_of() { _destination = Mapper.Map<int[]>(_source); } [Fact] public void Should_not_use_custom_mapper_but_probably_should() { for (var i = 0; i < _source.Length; i++) { _destination[i].ShouldBe(i + 1); } } } public class When_mapping_null_list_to_array: AutoMapperSpecBase { Destination _destination; class Source { public List<SourceItem> Items { get; set; } } class Destination { public DestinationItem[] Items { get; set; } } class SourceItem { public int Value { get; set; } } class DestinationItem { public int Value { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); cfg.CreateMap<SourceItem, DestinationItem>(); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source()); } [Fact] public void Should_map_ok() { _destination.Items.Length.ShouldBe(0); } } public class When_mapping_null_array_to_list : AutoMapperSpecBase { Destination _destination; class Source { public SourceItem[] Items { get; set; } } class Destination { public List<DestinationItem> Items { get; set; } } class SourceItem { public int Value { get; set; } } class DestinationItem { public int Value { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); cfg.CreateMap<SourceItem, DestinationItem>(); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source()); } [Fact] public void Should_map_ok() { _destination.Items.Count.ShouldBe(0); } } public class When_mapping_collections : AutoMapperSpecBase { Author mappedAuthor; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(delegate{}); protected override void Because_of() { dynamic authorDynamic = new ExpandoObject(); authorDynamic.Name = "Charles Dickens"; dynamic book1 = new ExpandoObject(); book1.Name = "Great Expectations"; dynamic book2 = new ExpandoObject(); book2.Name = "Oliver Twist"; authorDynamic.Books = new List<object> { book1, book2 }; mappedAuthor = Mapper.Map<Author>(authorDynamic); } [Fact] public void Should_map_by_item_type() { mappedAuthor.Name.ShouldBe("Charles Dickens"); mappedAuthor.Books[0].Name.ShouldBe("Great Expectations"); mappedAuthor.Books[1].Name.ShouldBe("Oliver Twist"); } public class Author { public string Name { get; set; } public Book[] Books { get; set; } } public class Book { public string Name { get; set; } } } public class When_mapping_to_an_existing_HashSet_typed_as_IEnumerable : AutoMapperSpecBase { private Destination _destination = new Destination(); public class Source { public int[] IntCollection { get; set; } = new int[0]; } public class Destination { public IEnumerable<int> IntCollection { get; set; } = new HashSet<int> { 1, 2, 3, 4, 5 }; public string Unmapped { get; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map(new Source(), _destination); } [Fact] public void Should_clear_the_destination() { _destination.IntCollection.Count().ShouldBe(0); } } public class When_mapping_to_an_existing_array_typed_as_IEnumerable : AutoMapperSpecBase { private Destination _destination = new Destination(); public class Source { public int[] IntCollection { get; set; } = new int[0]; } public class Destination { public IEnumerable<int> IntCollection { get; set; } = new[] { 1, 2, 3, 4, 5 }; } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map(new Source(), _destination); } [Fact] public void Should_create_destination_array_the_same_size_as_the_source() { _destination.IntCollection.Count().ShouldBe(0); } } public class When_mapping_to_a_concrete_non_generic_ienumerable : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } public List<int> Values2 { get; set; } } public class Destination { public IEnumerable Values { get; set; } public IEnumerable Values2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } [Fact] public void Should_map_from_the_generic_list_of_values() { _destination.Values2.ShouldNotBeNull(); _destination.Values2.ShouldContain(9); _destination.Values2.ShouldContain(8); _destination.Values2.ShouldContain(7); _destination.Values2.ShouldContain(6); } } public class When_mapping_to_a_concrete_generic_ienumerable : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } public List<int> Values2 { get; set; } } public class Destination { public IEnumerable<int> Values { get; set; } public IEnumerable<string> Values2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } [Fact] public void Should_map_from_the_generic_list_of_values_with_formatting() { _destination.Values2.ShouldNotBeNull(); _destination.Values2.ShouldContain("9"); _destination.Values2.ShouldContain("8"); _destination.Values2.ShouldContain("7"); _destination.Values2.ShouldContain("6"); } } public class When_mapping_to_a_getter_only_ienumerable : AutoMapperSpecBase { private Destination _destination = new Destination(); public class Source { public int[] Values { get; set; } public List<int> Values2 { get; set; } } public class Destination { public IEnumerable<int> Values { get; } = new List<int>(); public IEnumerable<string> Values2 { get; } = new List<string>(); } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() => _destination = Mapper.Map<Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }); [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldBe(new[] { 1, 2, 3, 4 }); _destination.Values2.ShouldBe(new[] { "9", "8", "7", "6" }); } } public class When_mapping_to_a_getter_only_existing_ienumerable : AutoMapperSpecBase { private Destination _destination = new Destination(); public class Source { public int[] Values { get; set; } public List<int> Values2 { get; set; } } public class Destination { public IEnumerable<int> Values { get; } = new List<int>(); public IEnumerable<string> Values2 { get; } = new List<string>(); } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() => Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }, _destination); [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldBe(new[] { 1, 2, 3, 4 }); _destination.Values2.ShouldBe(new[]{ "9", "8", "7", "6" }); } } public class When_mapping_to_a_concrete_non_generic_icollection : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } public List<int> Values2 { get; set; } } public class Destination { public ICollection Values { get; set; } public ICollection Values2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } [Fact] public void Should_map_from_a_non_array_source() { _destination.Values2.ShouldNotBeNull(); _destination.Values2.ShouldContain(9); _destination.Values2.ShouldContain(8); _destination.Values2.ShouldContain(7); _destination.Values2.ShouldContain(6); } } public class When_mapping_to_a_concrete_generic_icollection : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } } public class Destination { public ICollection<string> Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain("1"); _destination.Values.ShouldContain("2"); _destination.Values.ShouldContain("3"); _destination.Values.ShouldContain("4"); } } public class When_mapping_to_a_concrete_ilist : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } } public class Destination { public IList Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } } public class When_mapping_to_a_concrete_generic_ilist : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } } public class Destination { public IList<string> Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain("1"); _destination.Values.ShouldContain("2"); _destination.Values.ShouldContain("3"); _destination.Values.ShouldContain("4"); } } public class When_mapping_to_a_custom_list_with_the_same_type : AutoMapperSpecBase { private Destination _destination; private Source _source; public class ValueCollection : Collection<int> { } public class Source { public ValueCollection Values { get; set; } } public class Destination { public ValueCollection Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _source = new Source { Values = new ValueCollection { 1, 2, 3, 4 } }; _destination = Mapper.Map<Source, Destination>(_source); } [Fact] public void Should_assign_the_value_directly() { _source.Values.ShouldBe(_destination.Values); } } public class When_mapping_to_a_custom_collection_with_the_same_type_not_implementing_IList : AutoMapperSpecBase { private Source _source; private Destination _destination; public class ValueCollection : IEnumerable<int> { private List<int> implementation = new List<int>(); public ValueCollection(IEnumerable<int> items) { implementation = items.ToList(); } public IEnumerator<int> GetEnumerator() { return implementation.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)implementation).GetEnumerator(); } } public class Source { public ValueCollection Values { get; set; } } public class Destination { public ValueCollection Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Establish_context() { _source = new Source { Values = new ValueCollection(new[] { 1, 2, 3, 4 }) }; } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(_source); } [Fact] public void Should_map_the_list_of_source_items() { // here not the EnumerableMapper is used, but just the AssignableMapper! _destination.Values.ShouldBeSameAs(_source.Values); _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } } public class When_mapping_to_a_collection_with_instantiation_managed_by_the_destination : AutoMapperSpecBase { private Destination _destination; private Source _source; public class SourceItem { public int Value { get; set; } } public class DestItem { public int Value { get; set; } } public class Source { public List<SourceItem> Values { get; set; } } public class Destination { private List<DestItem> _values = new List<DestItem>(); public List<DestItem> Values { get { return _values; } } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Values, opt => opt.UseDestinationValue()); cfg.CreateMap<SourceItem, DestItem>(); }); protected override void Because_of() { _source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } }; _destination = Mapper.Map<Source, Destination>(_source); } [Fact] public void Should_assign_the_value_directly() { _destination.Values.Count.ShouldBe(2); _destination.Values[0].Value.ShouldBe(5); _destination.Values[1].Value.ShouldBe(10); } } public class When_mapping_to_an_existing_list_with_existing_items : AutoMapperSpecBase { private Destination _destination; private Source _source; public class SourceItem { public int Value { get; set; } } public class DestItem { public int Value { get; set; } } public class Source { public List<SourceItem> Values { get; set; } } public class Destination { private List<DestItem> _values = new List<DestItem>(); public List<DestItem> Values { get { return _values; } } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Values, opt => opt.UseDestinationValue()); cfg.CreateMap<SourceItem, DestItem>(); }); protected override void Because_of() { _source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } }; _destination = new Destination(); _destination.Values.Add(new DestItem()); Mapper.Map(_source, _destination); } [Fact] public void Should_clear_the_list_before_mapping() { _destination.Values.Count.ShouldBe(2); } } public class When_mapping_a_collection_with_null_members : AutoMapperSpecBase { const string FirstString = null; private IEnumerable<string> _strings = new List<string> { FirstString }; private List<string> _mappedStrings = new List<string>(); protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.AllowNullDestinationValues = true; }); protected override void Because_of() { _mappedStrings = Mapper.Map<IEnumerable<string>, List<string>>(_strings); } [Fact] public void Should_map_correctly() { _mappedStrings.ShouldNotBeNull(); _mappedStrings.Count.ShouldBe(1); _mappedStrings[0].ShouldBeNull(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Expressions.Xml { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Xml; using Bond.Expressions; using Bond.Expressions.Pull; using Bond.Protocols; public class SimpleXmlParser<R> : XmlParser<R> where R : IXmlReader { static readonly Expression<Action<byte, XmlNodeType, string, string>> parsingError = (s, t, n, v) => ParsingError(s, t, n, v); static readonly Expression<Action<XmlNodeType>> unexpectedNodeError = n => UnexpectedNodeError(n); delegate Expression ContainerItemHandler(Expression nextItem); public SimpleXmlParser(RuntimeSchema schema) : base(schema, flatten: true) {} public SimpleXmlParser(Type type) : base(Bond.Schema.GetRuntimeSchema(type), flatten: true) {} SimpleXmlParser(XmlParser<R> that, RuntimeSchema schema) : base(that, schema, flatten: true) {} protected override IStateMachine<XmlNodeType> CreateStateMachine( IEnumerable<TransformSchemaPair> transforms, ParameterExpression requiredFields) { return new StateMachine<XmlNodeType> { InitialState = State.AtStructElement, FinalState = State.Finished, IgnoredTokens = new[] { XmlNodeType.Comment, XmlNodeType.Text, XmlNodeType.Whitespace, XmlNodeType.XmlDeclaration, }, Default = state => Expression.Invoke(unexpectedNodeError, Reader.NodeType), TokenTransitions = new[] { new TokenTransition<XmlNodeType> { Token = XmlNodeType.Element, StateTransitions = new[] { new StateTransition(State.AtStructElement, ProcessStructElement), new StateTransition(State.InsideStructElement, state => ProcessFieldElement(state, requiredFields, transforms)), new StateTransition(State.AtFieldEndElement, State.InsideStructElement, state => Reader.Read()) }, Default = state => ParsingError(state), }, new TokenTransition<XmlNodeType> { Token = XmlNodeType.EndElement, StateTransitions = new[] { new StateTransition(State.AtFieldEndElement, State.InsideStructElement, state => Reader.Read()), new StateTransition(State.InsideStructElement, State.Finished, state => Reader.Read()) }, Default = state => ParsingError(state), } } }; } Expression ProcessStructElement(Expression state) { return Expression.Block( Expression.IfThenElse( Reader.IsEmptyElement, Expression.Assign(state, Expression.Constant(State.Finished)), Expression.Assign(state, Expression.Constant(State.InsideStructElement))), Reader.Read()); } Expression ProcessFieldElement( Expression state, ParameterExpression requiredFields, IEnumerable<TransformSchemaPair> transforms) { var requiredIndex = 0; // start from the expression to handle unknown element (will be executed at the end of the if/else chain) Expression body = Expression.Block( Reader.Skip(), Expression.Assign(state, Expression.Constant(State.InsideStructElement))); // if there are transform/schema pairs for base structs, process their fields as well into the expression foreach (var pair in transforms) { var index = 0; var structDef = pair.Schema.StructDef; foreach (var field in pair.Transform.Fields) { var fieldDef = structDef.fields[index++]; Debug.Assert(field.Id == fieldDef.id); var parser = new SimpleXmlParser<R>(this, pair.Schema.GetFieldSchema(fieldDef)); // process field - and set the state to expect to see the field element's end var handleField = new List<Expression> { field.Value(parser, Expression.Constant(fieldDef.type.id)), Expression.Assign(state, Expression.Constant(State.AtFieldEndElement)) }; if (fieldDef.metadata.modifier == Modifier.Required) { handleField.Add(RequiredFields.Mark(requiredFields, requiredIndex++)); } body = Expression.IfThenElse( NodeNameEquals(fieldDef.metadata.name, structDef.metadata.GetXmlNamespace()), Expression.Block(handleField), body); } } return body; } public override Expression Apply(ITransform transform) { // in SimpleXml protocol, the parser is expecting to read one step in order to get to the actual // element that represents the struct return Expression.Block( Read(), base.Apply(transform)); } public override Expression Blob(Expression count) { // TODO: for now handle blob as array of bytes; consider CDATA return null; } public override Expression Scalar(Expression valueType, BondDataType expectedType, ValueHandler handler) { var stringValue = Expression.Variable(typeof(string), "valueAsString"); // Reading primitive field of a struct, or a primitive list item - value is in Xml element text. // If we have an empty element, parse it as if it has an empty text. // Otherwise: read once to get to the text, handle the text, read once more to get to the end element. return Expression.Block( new[] { stringValue }, Expression.IfThenElse( Reader.IsEmptyElement, Expression.Assign(stringValue, StringExpression.Empty()), Expression.Block( Reader.Read(), Expression.IfThenElse( Expression.Equal(Reader.NodeType, Expression.Constant(XmlNodeType.EndElement)), Expression.Assign(stringValue, Expression.Constant(string.Empty)), Expression.Block( IfNotNodeType(XmlNodeType.Text, IfNotNodeType(XmlNodeType.Whitespace, ParsingError())), Expression.Assign(stringValue, Reader.Value), Reader.Read(), IfNotNodeType(XmlNodeType.EndElement, ParsingError()))))), handler(StringExpression.Convert(stringValue, expectedType))); } public override Expression Container(BondDataType? expectedType, ContainerHandler handler) { return Items(nextItem => handler( new SimpleXmlParser<R>(this, Schema.GetElementSchema()), Expression.Constant(Schema.TypeDef.element.id), nextItem, Expression.Constant(0))); } public override Expression Map(BondDataType? expectedKeyType, BondDataType? expectedValueType, MapHandler handler) { return Items(nextItem => handler( new SimpleXmlParser<R>(this, Schema.GetKeySchema()), new SimpleXmlParser<R>(this, Schema.GetElementSchema()), Expression.Constant(Schema.TypeDef.key.id), Expression.Constant(Schema.TypeDef.element.id), nextItem, nextItem, Expression.Constant(0))); } Expression Items(ContainerItemHandler handler) { // If the list is an empty element we won't read anything var isEmpty = Expression.Variable(typeof(bool), "isEmpty"); // Generate the following code for the "next" expression: // if (isEmpty) // { // return false; // } // else // { // while (reader.NodeType == XmlNodeType.Whitespace) reader.Read; // do { reader.Read(); } while (reader.NodeType == XmlNodeType.Whitespace; // // if (reader.NodeType == XmlNodeType.Element) && // reader.LocalName != "Item") // { // throw new InvalidDataException(); // } // // return reader.XmlNode != XmlNodeType.EndElement; // } var whitespace = Expression.Equal(Reader.NodeType, Expression.Constant(XmlNodeType.Whitespace)); var next = Expression.Condition(isEmpty, Expression.Constant(false), Expression.Block( ControlExpression.While(whitespace, Reader.Read()), ControlExpression.DoWhile(Reader.Read(), whitespace), Expression.IfThen( Expression.AndAlso( Expression.Equal(Reader.NodeType, Expression.Constant(XmlNodeType.Element)), Expression.NotEqual(Reader.LocalName, Expression.Constant("Item"))), ParsingError()), Expression.NotEqual(Reader.NodeType, Expression.Constant(XmlNodeType.EndElement)))); return Expression.Block( new[] { isEmpty }, Expression.Assign(isEmpty, Reader.IsEmptyElement), handler(next)); } Expression IfNotNodeType(XmlNodeType type, Expression then) { return Expression.IfThen( Expression.NotEqual(Reader.NodeType, Expression.Constant(type)), then); } Expression NodeNameEquals(string localName, string namespaceUri) { if (string.IsNullOrEmpty(namespaceUri)) { return StringExpression.Equals(Reader.LocalName, localName, StringComparison.OrdinalIgnoreCase); } return Expression.AndAlso( StringExpression.Equals(Reader.LocalName, localName, StringComparison.OrdinalIgnoreCase), Expression.OrElse( StringExpression.Equals(Reader.NamespaceURI, StringExpression.Empty(), StringComparison.OrdinalIgnoreCase), StringExpression.Equals(Reader.NamespaceURI, namespaceUri, StringComparison.OrdinalIgnoreCase))); } static void UnexpectedNodeError(XmlNodeType type) { throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "Unexpected node type: {0}", type)); } Expression ParsingError(Expression state) { return Expression.Invoke(parsingError, state, Reader.NodeType, Reader.LocalName, Reader.Value); } Expression ParsingError() { return Expression.Invoke(parsingError, Expression.Constant((byte)0), Reader.NodeType, Reader.LocalName, Reader.Value); } [MethodImpl(MethodImplOptions.NoInlining)] static void ParsingError(byte state, XmlNodeType type, string name, string value) { throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "Parsing error: state '{0}', (Xml node type='{1}', name='{2}', value='{3}')", state, type, name, value)); } static class State { public const byte AtStructElement = 1; public const byte InsideStructElement = 2; public const byte AtFieldEndElement = 3; public const byte Finished = 4; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace ParquetSharp.Column.Impl { using System; using System.IO; using ParquetSharp.Bytes; using ParquetSharp.Column.Page; using ParquetSharp.Column.Values; using ParquetSharp.Column.Values.Rle; using ParquetSharp.External; using ParquetSharp.IO; using ParquetSharp.IO.Api; using ParquetSharp.Schema; /** * ColumnReader implementation * * @author Julien Le Dem * */ public class ColumnReaderImpl : ColumnReader { private static readonly Log LOG = Log.getLog(typeof(ColumnReaderImpl)); /** * binds the lower level page decoder to the record converter materializing the records * * @author Julien Le Dem * */ private abstract class Binding { /** * read one value from the underlying page */ public abstract void read(); /** * skip one value from the underlying page */ public abstract void skip(); /** * write current value to converter */ public abstract void writeValue(); /** * @return current value */ public virtual int getDictionaryId() { throw new NotSupportedException(); } /** * @return current value */ public virtual int getInteger() { throw new NotSupportedException(); } /** * @return current value */ public virtual bool getBoolean() { throw new NotSupportedException(); } /** * @return current value */ public virtual long getLong() { throw new NotSupportedException(); } /** * @return current value */ public virtual Binary getBinary() { throw new NotSupportedException(); } /** * @return current value */ public virtual float getFloat() { throw new NotSupportedException(); } /** * @return current value */ public virtual double getDouble() { throw new NotSupportedException(); } } private readonly VersionParser.ParsedVersion writerVersion; private readonly ColumnDescriptor path; private readonly long totalValueCount; private readonly PageReader pageReader; private readonly Dictionary dictionary; private IntIterator repetitionLevelColumn; private IntIterator definitionLevelColumn; protected ValuesReader dataColumn; private Encoding currentEncoding; private int repetitionLevel; private int definitionLevel; private int dictionaryId; private long endOfPageValueCount; private int readValues = 0; private int pageValueCount = 0; private readonly PrimitiveConverter converter; private Binding binding; // this is needed because we will attempt to read the value twice when filtering // TODO: rework that private bool valueRead; private void bindToDictionary(Dictionary dictionary) { binding = new DictionaryBinding(this, dictionary); } class DictionaryBinding : Binding { private readonly ColumnReaderImpl reader; private readonly Dictionary dictionary; public DictionaryBinding(ColumnReaderImpl reader, Dictionary dictionary) { this.reader = reader; this.dictionary = dictionary; } public override void read() { reader.dictionaryId = reader.dataColumn.readValueDictionaryId(); } public override void skip() { reader.dataColumn.skip(); } public override int getDictionaryId() { return reader.dictionaryId; } public override void writeValue() { reader.converter.addValueFromDictionary(reader.dictionaryId); } public override int getInteger() { return dictionary.decodeToInt(reader.dictionaryId); } public override bool getBoolean() { return dictionary.decodeToBoolean(reader.dictionaryId); } public override long getLong() { return dictionary.decodeToLong(reader.dictionaryId); } public override Binary getBinary() { return dictionary.decodeToBinary(reader.dictionaryId); } public override float getFloat() { return dictionary.decodeToFloat(reader.dictionaryId); } public override double getDouble() { return dictionary.decodeToDouble(reader.dictionaryId); } } private void bind(PrimitiveType.PrimitiveTypeName type) { binding = type.convert(new PrimitiveTypeNameBinding(this)); } class PrimitiveTypeNameBinding : PrimitiveType.PrimitiveTypeNameConverter<Binding> { private readonly ColumnReaderImpl reader; public PrimitiveTypeNameBinding(ColumnReaderImpl reader) { this.reader = reader; } public Binding convertFLOAT(PrimitiveType.PrimitiveTypeName primitiveTypeName) { return new FloatBinding(this.reader); } class FloatBinding : Binding { private readonly ColumnReaderImpl reader; private float current; public FloatBinding(ColumnReaderImpl reader) { this.reader = reader; } public override void read() { current = reader.dataColumn.readFloat(); } public override void skip() { current = 0; reader.dataColumn.skip(); } public override float getFloat() { return current; } public override void writeValue() { reader.converter.addFloat(current); } } public Binding convertDOUBLE(PrimitiveType.PrimitiveTypeName primitiveTypeName) { return new DoubleBinding(this.reader); } class DoubleBinding : Binding { private readonly ColumnReaderImpl reader; private double current; public DoubleBinding(ColumnReaderImpl reader) { this.reader = reader; } public override void read() { current = reader.dataColumn.readDouble(); } public override void skip() { current = 0; reader.dataColumn.skip(); } public override double getDouble() { return current; } public override void writeValue() { reader.converter.addDouble(current); } } public Binding convertINT32(PrimitiveType.PrimitiveTypeName primitiveTypeName) { return new IntBinding(this.reader); } class IntBinding : Binding { private readonly ColumnReaderImpl reader; private int current; public IntBinding(ColumnReaderImpl reader) { this.reader = reader; } public override void read() { current = reader.dataColumn.readInteger(); } public override void skip() { current = 0; reader.dataColumn.skip(); } public override int getInteger() { return current; } public override void writeValue() { reader.converter.addInt(current); } } public Binding convertINT64(PrimitiveType.PrimitiveTypeName primitiveTypeName) { return new LongBinding(this.reader); } class LongBinding : Binding { private readonly ColumnReaderImpl reader; private long current; public LongBinding(ColumnReaderImpl reader) { this.reader = reader; } public override void read() { current = reader.dataColumn.readLong(); } public override void skip() { current = 0; reader.dataColumn.skip(); } public override long getLong() { return current; } public override void writeValue() { reader.converter.addLong(current); } } public Binding convertINT96(PrimitiveType.PrimitiveTypeName primitiveTypeName) { return this.convertBINARY(primitiveTypeName); } public Binding convertFIXED_LEN_BYTE_ARRAY(PrimitiveType.PrimitiveTypeName primitiveTypeName) { return this.convertBINARY(primitiveTypeName); } public Binding convertBOOLEAN(PrimitiveType.PrimitiveTypeName primitiveTypeName) { return new BooleanBinding(this.reader); } class BooleanBinding : Binding { private readonly ColumnReaderImpl reader; private bool current; public BooleanBinding(ColumnReaderImpl reader) { this.reader = reader; } public override void read() { current = reader.dataColumn.readBoolean(); } public override void skip() { current = false; reader.dataColumn.skip(); } public override bool getBoolean() { return current; } public override void writeValue() { reader.converter.addBoolean(current); } } public Binding convertBINARY(PrimitiveType.PrimitiveTypeName primitiveTypeName) { return new BinaryBinding(this.reader); } class BinaryBinding : Binding { private readonly ColumnReaderImpl reader; private Binary current; public BinaryBinding(ColumnReaderImpl reader) { this.reader = reader; } public override void read() { current = reader.dataColumn.readBytes(); } public override void skip() { current = null; reader.dataColumn.skip(); } public override Binary getBinary() { return current; } public override void writeValue() { reader.converter.addBinary(current); } } } /** * creates a reader for triplets * @param path the descriptor for the corresponding column * @param pageReader the underlying store to read from */ public ColumnReaderImpl(ColumnDescriptor path, PageReader pageReader, PrimitiveConverter converter, VersionParser.ParsedVersion writerVersion) { this.path = Preconditions.checkNotNull(path, "path"); this.pageReader = Preconditions.checkNotNull(pageReader, "pageReader"); this.converter = Preconditions.checkNotNull(converter, "converter"); this.writerVersion = writerVersion; DictionaryPage dictionaryPage = pageReader.readDictionaryPage(); if (dictionaryPage != null) { try { this.dictionary = dictionaryPage.getEncoding().initDictionary(path, dictionaryPage); if (converter.hasDictionarySupport()) { converter.setDictionary(dictionary); } } catch (IOException e) { throw new ParquetDecodingException("could not decode the dictionary for " + path, e); } } else { this.dictionary = null; } this.totalValueCount = pageReader.getTotalValueCount(); if (totalValueCount == 0) { throw new ParquetDecodingException("totalValueCount == 0"); } consume(); } private bool isFullyConsumed() { return readValues >= totalValueCount; } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#writeCurrentValueToConverter() */ public void writeCurrentValueToConverter() { readValue(); this.binding.writeValue(); } public int getCurrentValueDictionaryID() { readValue(); return binding.getDictionaryId(); } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getInteger() */ public int getInteger() { readValue(); return this.binding.getInteger(); } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getBoolean() */ public bool getBoolean() { readValue(); return this.binding.getBoolean(); } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getLong() */ public long getLong() { readValue(); return this.binding.getLong(); } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getBinary() */ public Binary getBinary() { readValue(); return this.binding.getBinary(); } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getFloat() */ public float getFloat() { readValue(); return this.binding.getFloat(); } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getDouble() */ public double getDouble() { readValue(); return this.binding.getDouble(); } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getCurrentRepetitionLevel() */ public int getCurrentRepetitionLevel() { return repetitionLevel; } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getDescriptor() */ public ColumnDescriptor getDescriptor() { return path; } /** * Reads the value into the binding. */ public void readValue() { try { if (!valueRead) { binding.read(); valueRead = true; } } catch (Exception e) { if (CorruptDeltaByteArrays.requiresSequentialReads(writerVersion, currentEncoding) && e is IndexOutOfRangeException) { // this is probably PARQUET-246, which may happen if reading data with // MR because this can't be detected without reading all footers throw new ParquetDecodingException("Read failure possibly due to " + "PARQUET-246: try setting parquet.split.files to false", new ParquetDecodingException( string.Format("Can't read value in column {0} at value {1} out of {2}, " + "{3} out of {4} in currentPage. repetition level: " + "{5}, definition level: {6}", path, readValues, totalValueCount, readValues - (endOfPageValueCount - pageValueCount), pageValueCount, repetitionLevel, definitionLevel), e)); } throw new ParquetDecodingException( string.Format("Can't read value in column {0} at value {1} out of {2}, " + "{3} out of {4} in currentPage. repetition level: " + "{5}, definition level: {6}", path, readValues, totalValueCount, readValues - (endOfPageValueCount - pageValueCount), pageValueCount, repetitionLevel, definitionLevel), e); } } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#skip() */ public void skip() { if (!valueRead) { binding.skip(); valueRead = true; } } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getCurrentDefinitionLevel() */ public int getCurrentDefinitionLevel() { return definitionLevel; } // TODO: change the logic around read() to not tie together reading from the 3 columns private void readRepetitionAndDefinitionLevels() { repetitionLevel = repetitionLevelColumn.nextInt(); definitionLevel = definitionLevelColumn.nextInt(); ++readValues; } private void checkRead() { if (isPageFullyConsumed()) { if (isFullyConsumed()) { if (Log.DEBUG) LOG.debug("end reached"); repetitionLevel = 0; // the next repetition level return; } readPage(); } readRepetitionAndDefinitionLevels(); } private void readPage() { if (Log.DEBUG) LOG.debug("loading page"); DataPage page = pageReader.readPage(); page.accept(new DataPageReaderVisitor(this)); } class DataPageReaderVisitor : DataPage.Visitor<object> { private readonly ColumnReaderImpl reader; public DataPageReaderVisitor(ColumnReaderImpl reader) { this.reader = reader; } public object visit(DataPageV1 dataPageV1) { reader.readPageV1(dataPageV1); return null; } public object visit(DataPageV2 dataPageV2) { reader.readPageV2(dataPageV2); return null; } } private void initDataReader(Encoding dataEncoding, ByteBuffer bytes, int offset, int valueCount) { ValuesReader previousReader = this.dataColumn; this.currentEncoding = dataEncoding; this.pageValueCount = valueCount; this.endOfPageValueCount = readValues + pageValueCount; if (dataEncoding.usesDictionary()) { if (dictionary == null) { throw new ParquetDecodingException( "could not read page in col " + path + " as the dictionary was missing for encoding " + dataEncoding); } this.dataColumn = dataEncoding.getDictionaryBasedValuesReader(path, ValuesType.VALUES, dictionary); } else { this.dataColumn = dataEncoding.getValuesReader(path, ValuesType.VALUES); } if (dataEncoding.usesDictionary() && converter.hasDictionarySupport()) { bindToDictionary(dictionary); } else { bind(path.getType()); } try { dataColumn.initFromPage(pageValueCount, bytes, offset); } catch (IOException e) { throw new ParquetDecodingException("could not read page in col " + path, e); } if (CorruptDeltaByteArrays.requiresSequentialReads(writerVersion, dataEncoding) && previousReader != null && previousReader is RequiresPreviousReader) { // previous reader can only be set if reading sequentially ((RequiresPreviousReader)dataColumn).setPreviousReader(previousReader); } } private void readPageV1(DataPageV1 page) { ValuesReader rlReader = page.getRlEncoding().getValuesReader(path, ValuesType.REPETITION_LEVEL); ValuesReader dlReader = page.getDlEncoding().getValuesReader(path, ValuesType.DEFINITION_LEVEL); this.repetitionLevelColumn = new ValuesReaderIntIterator(rlReader); this.definitionLevelColumn = new ValuesReaderIntIterator(dlReader); try { ByteBuffer bytes = page.getBytes().toByteBuffer(); if (Log.DEBUG) LOG.debug("page size " + bytes.remaining() + " bytes and " + pageValueCount + " records"); if (Log.DEBUG) LOG.debug("reading repetition levels at 0"); rlReader.initFromPage(pageValueCount, bytes, 0); int next = rlReader.getNextOffset(); if (Log.DEBUG) LOG.debug("reading definition levels at " + next); dlReader.initFromPage(pageValueCount, bytes, next); next = dlReader.getNextOffset(); if (Log.DEBUG) LOG.debug("reading data at " + next); initDataReader(page.getValueEncoding(), bytes, next, page.getValueCount()); } catch (IOException e) { throw new ParquetDecodingException("could not read page " + page + " in col " + path, e); } } private void readPageV2(DataPageV2 page) { this.repetitionLevelColumn = newRLEIterator(path.getMaxRepetitionLevel(), page.getRepetitionLevels()); this.definitionLevelColumn = newRLEIterator(path.getMaxDefinitionLevel(), page.getDefinitionLevels()); try { if (Log.DEBUG) LOG.debug("page data size " + page.getData().size() + " bytes and " + pageValueCount + " records"); initDataReader(page.getDataEncoding(), page.getData().toByteBuffer(), 0, page.getValueCount()); } catch (IOException e) { throw new ParquetDecodingException("could not read page " + page + " in col " + path, e); } } private IntIterator newRLEIterator(int maxLevel, BytesInput bytes) { try { if (maxLevel == 0) { return new NullIntIterator(); } return new RLEIntIterator( new RunLengthBitPackingHybridDecoder( BytesUtils.getWidthFromMaxInt(maxLevel), bytes.toInputStream())); } catch (IOException e) { throw new ParquetDecodingException("could not read levels in page for col " + path, e); } } private bool isPageFullyConsumed() { return readValues >= endOfPageValueCount; } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#consume() */ public void consume() { checkRead(); valueRead = false; } /** * {@inheritDoc} * @see org.apache.parquet.column.ColumnReader#getTotalValueCount() */ public long getTotalValueCount() { return totalValueCount; } abstract class IntIterator { public abstract int nextInt(); } class ValuesReaderIntIterator : IntIterator { private readonly ValuesReader @delegate; public ValuesReaderIntIterator(ValuesReader @delegate) { this.@delegate = @delegate; } public override int nextInt() { return @delegate.readInteger(); } } class RLEIntIterator : IntIterator { private readonly RunLengthBitPackingHybridDecoder @delegate; public RLEIntIterator(RunLengthBitPackingHybridDecoder @delegate) { this.@delegate = @delegate; } public override int nextInt() { try { return @delegate.readInt(); } catch (IOException e) { throw new ParquetDecodingException(e); } } } sealed private class NullIntIterator : IntIterator { public override int nextInt() { return 0; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: FileSystemInfo ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: ** ** ===========================================================*/ using System; using System.Collections; using System.Security; using System.Security.Permissions; using Microsoft.Win32; using System.Text; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.IO { [Serializable] #if !FEATURE_CORECLR [FileIOPermissionAttribute(SecurityAction.InheritanceDemand,Unrestricted=true)] #endif [ComVisible(true)] #if FEATURE_REMOTING public abstract class FileSystemInfo : MarshalByRefObject, ISerializable { #else // FEATURE_REMOTING public abstract class FileSystemInfo : ISerializable { #endif //FEATURE_REMOTING [System.Security.SecurityCritical] // auto-generated internal Win32Native.WIN32_FILE_ATTRIBUTE_DATA _data; // Cache the file information internal int _dataInitialised = -1; // We use this field in conjunction with the Refresh methods, if we succeed // we store a zero, on failure we store the HResult in it so that we can // give back a generic error back. private const int ERROR_INVALID_PARAMETER = 87; internal const int ERROR_ACCESS_DENIED = 0x5; protected String FullPath; // fully qualified path of the directory protected String OriginalPath; // path passed in by the user private String _displayPath = ""; // path that can be displayed to the user #if FEATURE_CORECLR #if FEATURE_CORESYSTEM [System.Security.SecurityCritical] #else [System.Security.SecuritySafeCritical] #endif //FEATURE_CORESYSTEM #endif protected FileSystemInfo() { } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] protected FileSystemInfo(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); // Must use V1 field names here, since V1 didn't implement // ISerializable. FullPath = Path.GetFullPathInternal(info.GetString("FullPath")); OriginalPath = info.GetString("OriginalPath"); // Lazily initialize the file attributes. _dataInitialised = -1; } [System.Security.SecurityCritical] internal void InitializeFrom(Win32Native.WIN32_FIND_DATA findData) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); _data.PopulateFrom(findData); _dataInitialised = 0; } // Full path of the direcory/file public virtual String FullName { [System.Security.SecuritySafeCritical] get { String demandDir; if (this is DirectoryInfo) demandDir = Directory.GetDemandDir(FullPath, true); else demandDir = FullPath; #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir); sourceState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand(); #endif return FullPath; } } internal virtual String UnsafeGetFullName { [System.Security.SecurityCritical] get { String demandDir; if (this is DirectoryInfo) demandDir = Directory.GetDemandDir(FullPath, true); else demandDir = FullPath; #if !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand(); #endif return FullPath; } } public String Extension { get { // GetFullPathInternal would have already stripped out the terminating "." if present. int length = FullPath.Length; for (int i = length; --i >= 0;) { char ch = FullPath[i]; if (ch == '.') return FullPath.Substring(i, length - i); if (ch == Path.DirectorySeparatorChar || ch == Path.AltDirectorySeparatorChar || ch == Path.VolumeSeparatorChar) break; } return String.Empty; } } // For files name of the file is returned, for directories the last directory in hierarchy is returned if possible, // otherwise the fully qualified name s returned public abstract String Name { get; } // Whether a file/directory exists public abstract bool Exists { get; } // Delete a file/directory public abstract void Delete(); public DateTime CreationTime { get { // depends on the security check in get_CreationTimeUtc return CreationTimeUtc.ToLocalTime(); } set { CreationTimeUtc = value.ToUniversalTime(); } } [ComVisible(false)] public DateTime CreationTimeUtc { [System.Security.SecuritySafeCritical] get { #if FEATURE_CORECLR // get_CreationTime also depends on this security check FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath); sourceState.EnsureState(); #endif if (_dataInitialised == -1) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); } if (_dataInitialised != 0) // Refresh was unable to initialise the data __Error.WinIOError(_dataInitialised, DisplayPath); long fileTime = ((long)_data.ftCreationTimeHigh << 32) | _data.ftCreationTimeLow; return DateTime.FromFileTimeUtc(fileTime); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] set { if (this is DirectoryInfo) Directory.SetCreationTimeUtc(FullPath,value); else File.SetCreationTimeUtc(FullPath,value); _dataInitialised = -1; } } public DateTime LastAccessTime { get { // depends on the security check in get_LastAccessTimeUtc return LastAccessTimeUtc.ToLocalTime(); } set { LastAccessTimeUtc = value.ToUniversalTime(); } } [ComVisible(false)] public DateTime LastAccessTimeUtc { [System.Security.SecuritySafeCritical] get { #if FEATURE_CORECLR // get_LastAccessTime also depends on this security check FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath); sourceState.EnsureState(); #endif if (_dataInitialised == -1) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); } if (_dataInitialised != 0) // Refresh was unable to initialise the data __Error.WinIOError(_dataInitialised, DisplayPath); long fileTime = ((long)_data.ftLastAccessTimeHigh << 32) | _data.ftLastAccessTimeLow; return DateTime.FromFileTimeUtc(fileTime); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] set { if (this is DirectoryInfo) Directory.SetLastAccessTimeUtc(FullPath,value); else File.SetLastAccessTimeUtc(FullPath,value); _dataInitialised = -1; } } public DateTime LastWriteTime { get { // depends on the security check in get_LastWriteTimeUtc return LastWriteTimeUtc.ToLocalTime(); } set { LastWriteTimeUtc = value.ToUniversalTime(); } } [ComVisible(false)] public DateTime LastWriteTimeUtc { [System.Security.SecuritySafeCritical] get { #if FEATURE_CORECLR // get_LastWriteTime also depends on this security check FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath); sourceState.EnsureState(); #endif if (_dataInitialised == -1) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); } if (_dataInitialised != 0) // Refresh was unable to initialise the data __Error.WinIOError(_dataInitialised, DisplayPath); long fileTime = ((long)_data.ftLastWriteTimeHigh << 32) | _data.ftLastWriteTimeLow; return DateTime.FromFileTimeUtc(fileTime); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] set { if (this is DirectoryInfo) Directory.SetLastWriteTimeUtc(FullPath,value); else File.SetLastWriteTimeUtc(FullPath,value); _dataInitialised = -1; } } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public void Refresh() { _dataInitialised = File.FillAttributeInfo(FullPath, ref _data, false, false); } public FileAttributes Attributes { [System.Security.SecuritySafeCritical] get { #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath); sourceState.EnsureState(); #endif if (_dataInitialised == -1) { _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); Refresh(); // Call refresh to intialise the data } if (_dataInitialised != 0) // Refresh was unable to initialise the data __Error.WinIOError(_dataInitialised, DisplayPath); return (FileAttributes) _data.fileAttributes; } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif set { #if !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.Write, FullPath).Demand(); #endif bool r = Win32Native.SetFileAttributes(FullPath, (int) value); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr==ERROR_INVALID_PARAMETER) throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs")); // For whatever reason we are turning ERROR_ACCESS_DENIED into // ArgumentException here (probably done for some 9x code path). // We can't change this now but special casing the error message instead. if (hr == ERROR_ACCESS_DENIED) throw new ArgumentException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName")); __Error.WinIOError(hr, DisplayPath); } _dataInitialised = -1; } } [System.Security.SecurityCritical] // auto-generated_required [ComVisible(false)] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { #if !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.PathDiscovery, FullPath).Demand(); #endif info.AddValue("OriginalPath", OriginalPath, typeof(String)); info.AddValue("FullPath", FullPath, typeof(String)); } internal String DisplayPath { get { return _displayPath; } set { _displayPath = value; } } } }
using System; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.TextureAtlases; namespace MonoGame.Extended.BitmapFonts { public static class BitmapFontExtensions { /// <summary> /// Adds a string to a batch of sprites for rendering using the specified font, text, position, color, layer, /// and width (in pixels) where to wrap the text at. /// </summary> /// <remarks> /// <see cref="BitmapFont" /> objects are loaded from the Content Manager. See the <see cref="BitmapFont" /> class for /// more information. /// Before any calls to <see cref="DrawString" /> you must call <see cref="SpriteBatch.Begin" />. Once all calls to /// <see cref="DrawString" /> are complete, call <see cref="SpriteBatch.End" />. /// Use a newline character (\n) to draw more than one line of text. /// </remarks> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="layerDepth"> /// The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. /// Use SpriteSortMode if you want sprites to be sorted during drawing. /// </param> /// <param name="wrapWidth">The width (in pixels) where to wrap the text at.</param> public static void DrawString(this SpriteBatch spriteBatch, BitmapFont font, string text, Vector2 position, Color color, float layerDepth, int wrapWidth = int.MaxValue) { if (wrapWidth == int.MaxValue) DrawInternal(spriteBatch, font, text, position, color, layerDepth); else DrawWrapped(spriteBatch, font, text, position, color, wrapWidth, layerDepth); } /// <summary> /// Adds a string to a batch of sprites for rendering using the specified font, text, position, color, /// and width (in pixels) where to wrap the text at. The text is drawn on layer 0f. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="wrapWidth">The width (in pixels) where to wrap the text at.</param> public static void DrawString(this SpriteBatch spriteBatch, BitmapFont font, string text, Vector2 position, Color color, int wrapWidth = int.MaxValue) { if (wrapWidth == int.MaxValue) DrawInternal(spriteBatch, font, text, position, color, 0f); else DrawWrapped(spriteBatch, font, text, position, color, wrapWidth, 0f); } /// <summary> /// Adds a string to a batch of sprites for rendering using the specified font, text, position, color, rotation, /// origin, scale, effects and layer. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="rotation">Specifies the angle (in radians) to rotate the text about its origin.</param> /// <param name="origin">The origin for each letter; the default is (0,0) which represents the upper-left corner.</param> /// <param name="scalef">Scale factor.</param> /// <param name="effects">Effects to apply.</param> /// <param name="layerDepth"> /// The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. /// Use SpriteSortMode if you want sprites to be sorted during drawing. /// </param> public static void DrawString(this SpriteBatch spriteBatch, BitmapFont font, string text, Vector2 position, Color color, float rotation, Vector2 origin, float scalef, SpriteEffects effects, float layerDepth) { var scale = new Vector2(scalef, scalef); DrawInternal(spriteBatch, font, text, position, color, rotation, origin, scale, effects, layerDepth); } /// <summary> /// Adds a string to a batch of sprites for rendering using the specified font, text, position, color, rotation, /// origin, scale, effects and layer. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="rotation">Specifies the angle (in radians) to rotate the text about its origin.</param> /// <param name="origin">The origin for each letter; the default is (0,0) which represents the upper-left corner.</param> /// <param name="scale">Scale factor.</param> /// <param name="effects">Effects to apply.</param> /// <param name="layerDepth"> /// The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. /// Use SpriteSortMode if you want sprites to be sorted during drawing. /// </param> public static void DrawString(this SpriteBatch spriteBatch, BitmapFont font, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { DrawInternal(spriteBatch, font, text, position, color, rotation, origin, scale, effects, layerDepth); } /// <summary> /// Adds a string to a batch of sprites for rendering using the specified font, text, position, color, rotation, /// origin, scale, effects and layer. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="rotation">Specifies the angle (in radians) to rotate the text about its origin.</param> /// <param name="origin">The origin for each letter; the default is (0,0) which represents the upper-left corner.</param> /// <param name="scalef">Scale factor.</param> /// <param name="effects">Effects to apply.</param> /// <param name="layerDepth"> /// The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. /// Use SpriteSortMode if you want sprites to be sorted during drawing. /// </param> public static void DrawString(this SpriteBatch spriteBatch, BitmapFont font, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, float scalef, SpriteEffects effects, float layerDepth) { var scale = new Vector2(scalef, scalef); DrawInternal(spriteBatch, font, text.ToString(), position, color, rotation, origin, scale, effects, layerDepth); } /// <summary> /// Adds a string to a batch of sprites for rendering using the specified font, text, position, color, rotation, /// origin, scale, effects and layer. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="rotation">Specifies the angle (in radians) to rotate the text about its origin.</param> /// <param name="origin">The origin for each letter; the default is (0,0) which represents the upper-left corner.</param> /// <param name="scale">Scale factor.</param> /// <param name="effects">Effects to apply.</param> /// <param name="layerDepth"> /// The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. /// Use SpriteSortMode if you want sprites to be sorted during drawing. /// </param> public static void DrawString(this SpriteBatch spriteBatch, BitmapFont font, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { DrawInternal(spriteBatch, font, text.ToString(), position, color, rotation, origin, scale, effects, layerDepth); } /// <summary> /// Adds a string to a batch of sprites for rendering using the specified font, text, position, and color. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> public static void DrawString(this SpriteBatch spriteBatch, BitmapFont font, StringBuilder text, Vector2 position, Color color) { DrawInternal(spriteBatch, font, text.ToString(), position, color, 0f); } /// <summary> /// Method to handle wrapping text at a specified width. Passes onto the <see cref="DrawInto" /> method /// if the user passes in int.MaxValue as the width. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="wrapWidth">The width (in pixels) where to wrap the text at.</param> /// <param name="layerDepth"> /// The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. /// Use SpriteSortMode if you want sprites to be sorted during drawing. /// </param> private static void DrawWrapped(this SpriteBatch spriteBatch, BitmapFont font, string text, Vector2 position, Color color, int wrapWidth, float layerDepth) { HandleNullParameters(font, text); if (wrapWidth == int.MaxValue) { DrawInternal(spriteBatch, font, text, position, color, layerDepth); return; } // parse the text and wrap it at the specified width var dx = position.X; var dy = position.Y; var sentences = text.Split(new[] {'\n'}, StringSplitOptions.None); foreach (var sentence in sentences) { var words = sentence.Split(new[] {' '}, StringSplitOptions.None); for (var i = 0; i < words.Length; i++) { var word = words[i]; var size = font.GetStringRectangle(word, Vector2.Zero); if ((i != 0) && (dx + size.Width >= wrapWidth)) { dy += font.LineHeight; dx = position.X; } DrawInternal(spriteBatch, font, word, new Vector2(dx, dy), color, layerDepth); dx += size.Width; var spaceCharRegion = font.GetCharacterRegion(' '); if (i != words.Length - 1) dx += spaceCharRegion.XAdvance + font.LetterSpacing; else dx += spaceCharRegion.XOffset + spaceCharRegion.Width; } dx = position.X; dy += font.LineHeight; } } /// <summary> /// Draw text using most of the values with defaults. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="layerDepth"> /// The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. /// Use SpriteSortMode if you want sprites to be sorted during drawing. /// </param> private static void DrawInternal(this SpriteBatch spriteBatch, BitmapFont font, string text, Vector2 position, Color color, float layerDepth) { const float rotation = 0f; const SpriteEffects effects = SpriteEffects.None; var scale = Vector2.One; var origin = Vector2.Zero; DrawInternal(spriteBatch, font, text, position, color, rotation, origin, scale, effects, layerDepth); } /// <summary> /// Internal method that actually does the heavy lifting of drawing the text /// using all of the provided parameters. /// </summary> /// <param name="spriteBatch"></param> /// <param name="font">A font for displaying text.</param> /// <param name="text">The text message to display.</param> /// <param name="position">The location (in screen coordinates) to draw the text.</param> /// <param name="color"> /// The <see cref="Color" /> to tint a sprite. Use <see cref="Color.White" /> for full color with no /// tinting. /// </param> /// <param name="rotation">Specifies the angle (in radians) to rotate the text about its origin.</param> /// <param name="origin">The origin for each letter; the default is (0,0) which represents the upper-left corner.</param> /// <param name="scale">Scale factor.</param> /// <param name="effects">Effects to apply.</param> /// <param name="layerDepth"> /// The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. /// Use SpriteSortMode if you want sprites to be sorted during drawing. /// </param> private static void DrawInternal(this SpriteBatch spriteBatch, BitmapFont font, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { HandleNullParameters(font, text); var dx = position.X; var dy = position.Y; var codePoints = BitmapFont.GetUnicodeCodePoints(text).ToArray(); var positionOffset = Vector2.Zero; for (int i = 0, l = codePoints.Length; i < l; i++) { var character = codePoints[i]; var fontRegion = font.GetCharacterRegion(character); if (fontRegion != null) { var charPosition = new Vector2(dx + fontRegion.XOffset, dy + fontRegion.YOffset); var scaledCharPosition = charPosition*new Vector2(scale.X, scale.Y); if (i == 0) positionOffset = scaledCharPosition - charPosition; scaledCharPosition -= positionOffset; spriteBatch.Draw(fontRegion.TextureRegion, scaledCharPosition, color, rotation, origin, scale, effects, layerDepth); if (i != text.Length - 1) dx += fontRegion.XAdvance + font.LetterSpacing; else dx += fontRegion.XOffset + fontRegion.Width; } if (character != '\n') continue; dy += font.LineHeight; dx = position.X; } } /// <summary> /// Handles dealing with null properties that are essential to rendering the <see cref="BitmapFont" />. /// </summary> /// <param name="bitmapFont">All draw functions must have a <see cref="BitmapFont" /> to use.</param> /// <param name="text">All draw functions must have text to use.</param> private static void HandleNullParameters(BitmapFont bitmapFont, string text) { if (bitmapFont == null) throw new ArgumentNullException(nameof(bitmapFont), "No BitmapFont specified."); if (text == null) throw new ArgumentNullException(nameof(text), "No text string specified."); } } }
// 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. //--------------------------------------------------------------------------- // // Description: An MSBuild task that classify the input files to different // categories based on the input item's attributes. // //--------------------------------------------------------------------------- using System; using System.IO; using System.Collections.Generic; using System.Globalization; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using MS.Utility; using MS.Internal.Tasks; // Since we disable PreSharp warnings in this file, PreSharp warning is unknown to C# compiler. // We first need to disable warnings about unknown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 namespace Microsoft.Build.Tasks.Windows { /// <summary> /// The File Classification task puts all the input baml files, image files into different /// output resource groups, such as Resources for Main assembly and Resources for satellite /// assembly. /// </summary> public sealed class FileClassifier : Task { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Constructor /// </summary> public FileClassifier() : base(SR.SharedResourceManager) { // set default values for some non-required input items _culture = null; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// ITask Execute method /// </summary> /// <returns></returns> public override bool Execute() { bool ret = false; var mainEmbeddedList = new List<ITaskItem>(); var satelliteEmbeddedList = new List<ITaskItem>(); var clrEmbeddedResourceList = new List<ITaskItem>(); var clrSatelliteEmbeddedResourceList = new List<ITaskItem>(); try { TaskHelper.DisplayLogo(Log, nameof(FileClassifier)); ret = VerifyTaskInputs(); if (ret != false) { // Do the real work to classify input files. Classify(SourceFiles, mainEmbeddedList, satelliteEmbeddedList); if (CLRResourceFiles != null) { // Generate the output CLR embedded resource list. Classify(CLRResourceFiles, clrEmbeddedResourceList, clrSatelliteEmbeddedResourceList); } // move the arraylist to the TaskItem array. MainEmbeddedFiles = mainEmbeddedList.ToArray(); SatelliteEmbeddedFiles = satelliteEmbeddedList.ToArray(); CLREmbeddedResource = clrEmbeddedResourceList.ToArray(); CLRSatelliteEmbeddedResource = clrSatelliteEmbeddedResourceList.ToArray(); } } catch (Exception e) { // PreSharp Complaint 6500 - do not handle null-ref or SEH exceptions. if (e is NullReferenceException || e is SEHException) { throw; } else { string message; string errorId; errorId = Log.ExtractMessageCode(e.Message, out message); if (String.IsNullOrEmpty(errorId)) { errorId = UnknownErrorID; message = SR.Get(SRID.UnknownBuildError, message); } Log.LogError(null, errorId, null, null, 0, 0, 0, 0, message, null); } return false; } #pragma warning disable 6500 catch // Non-CLS compliant errors { Log.LogErrorWithCodeFromResources(SRID.NonClsError); return false; } #pragma warning restore 6500 return ret; } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// SourceFiles: List of Items thatare to be classified /// </summary> [Required] public ITaskItem [] SourceFiles { get; set; } /// <summary> /// Can have values (exe, or dll) /// </summary> [Required] public string OutputType { get; set; } /// <summary> /// Culture of the build. Can be null if the build is non-localizable /// </summary> public string Culture { get { return _culture != null ? _culture.ToLower(CultureInfo.InvariantCulture) : null; } set { _culture = value; } } /// <summary> /// The CLR resource file list. /// In Project file, those files will be define by type CLRResource. /// such as: <Item Type="CLRResources" Include=" ...." Loacalizable="false/true" /> /// </summary> /// <value></value> public ITaskItem[] CLRResourceFiles { get; set; } /// <summary> /// Output Item list for the CLR resources that will be saved in /// the main assembly. /// </summary> /// <value></value> [Output] public ITaskItem[] CLREmbeddedResource { get; set; } /// <summary> /// Output Item list for the CLR resources that will be saved in /// the satellite assembly. /// </summary> /// <value></value> [Output] public ITaskItem[] CLRSatelliteEmbeddedResource { get; set; } /// <summary> /// MainEmbeddedFiles /// /// Non-localizable resources which will be embedded into the Main assembly. /// </summary> [Output] public ITaskItem [] MainEmbeddedFiles { get; set; } /// <summary> /// SatelliteEmbeddedFiles /// /// Localizable files which are embedded to the Satellite assembly for the /// culture which is set in Culture property.. /// </summary> [Output] public ITaskItem [] SatelliteEmbeddedFiles { get; set; } #endregion Public Properties //------------------------------------------------------ // // Public Events // //------------------------------------------------------ //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // // Verify all the propety values set from project file. // If any input value is set wrongly, report appropriate build error // and return false. // private bool VerifyTaskInputs() { bool bValidInput = true; // // Verify different property values // // OutputType is marked as Required, it should never be null or emtpy. // otherwise, the task should have been failed before the code goes here. string targetType = OutputType.ToLowerInvariant( ); switch (targetType) { case SharedStrings.Library : case SharedStrings.Module : case SharedStrings.WinExe : case SharedStrings.Exe : break; default : Log.LogErrorWithCodeFromResources(SRID.TargetIsNotSupported, targetType); bValidInput = false; break; } // SourceFiles property is marked as Required. // MSBUILD Engine should have checked the setting for this property // so don't need to recheck here. if (TaskHelper.IsValidCultureName(Culture) == false) { Log.LogErrorWithCodeFromResources(SRID.InvalidCulture, Culture); bValidInput = false; } return bValidInput; } private void Classify(IEnumerable<ITaskItem> inputItems, List<ITaskItem> mainList, List<ITaskItem> satelliteList) { foreach (ITaskItem inputItem in inputItems) { ITaskItem outputItem = new TaskItem { ItemSpec = inputItem.ItemSpec, }; // Selectively copy metadata over. outputItem.SetMetadata(SharedStrings.Link, inputItem.GetMetadata(SharedStrings.Link)); outputItem.SetMetadata(SharedStrings.LogicalName, inputItem.GetMetadata(SharedStrings.LogicalName)); if (IsItemLocalizable(inputItem)) { satelliteList.Add(outputItem); } else { mainList.Add(outputItem); } } } // <summary> // Check if the item is localizable or not. // </summary> // <param name="fileItem"></param> // <returns></returns> private bool IsItemLocalizable(ITaskItem fileItem) { bool isLocalizable = false; // if the default culture is not set, by default all // the items are not localizable. if (Culture != null && Culture.Equals("") == false) { string localizableString; // Default culture is set, by default the item is localizable // unless it is set as false in the Localizable attribute. isLocalizable = true; localizableString = fileItem.GetMetadata(SharedStrings.Localizable); if (localizableString != null && String.Compare(localizableString, "false", StringComparison.OrdinalIgnoreCase) ==0 ) { isLocalizable = false; } } return isLocalizable; } #endregion Private Methods //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private string _culture; private const string UnknownErrorID = "FC1000"; #endregion Private Fields } }
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; using System; using System.Collections.Generic; namespace com.bytewild.imaging.cropper { public class CropImageView : ImageViewTouchBase { #region Private members private List<HighlightView> hightlightViews = new List<HighlightView>(); private HighlightView mMotionHighlightView = null; private float mLastX; private float mLastY; private CropHandle mLastCropHandle; private global::com.bytewild.imaging.cropper.HighlightView.HitPosition motionEdge; private Context context; #endregion #region Constructor public CropImageView(Context context, IAttributeSet attrs) : base(context, attrs) { SetLayerType(Android.Views.LayerType.Software, null); this.context = context; } #endregion #region Public methods public void ClearHighlightViews() { this.hightlightViews.Clear(); } public void AddHighlightView(HighlightView hv) { hightlightViews.Add(hv); Invalidate(); } #endregion #region Overrides protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); for (int i = 0; i < hightlightViews.Count; i++) { hightlightViews[i].Draw(canvas); } } protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { base.OnLayout(changed, left, top, right, bottom); if (bitmapDisplayed.Bitmap != null) { foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); if (hv.Focused) { centerBasedOnHighlightView(hv); } } } } protected override void ZoomTo(float scale, float centerX, float centerY) { base.ZoomTo(scale, centerX, centerY); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void ZoomIn() { base.ZoomIn(); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void ZoomOut() { base.ZoomOut(); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void PostTranslate(float deltaX, float deltaY) { base.PostTranslate(deltaX, deltaY); for (int i = 0; i < hightlightViews.Count; i++) { HighlightView hv = hightlightViews[i]; hv.matrix.PostTranslate(deltaX, deltaY); hv.Invalidate(); } } public override bool OnTouchEvent(MotionEvent ev) { CropImageActivity cropImageActivity = (CropImageActivity)context; switch (ev.Action) { case MotionEventActions.Down: for (int i = 0; i < hightlightViews.Count; i++) { HighlightView hv = hightlightViews[i]; var cropHandle = hv.GetHit(ev.GetX(), ev.GetY()); if (cropHandle != null) { mMotionHighlightView = hv; mLastX = ev.GetX(); mLastY = ev.GetY(); mLastCropHandle = cropHandle; break; } } break; case MotionEventActions.Up: break; case MotionEventActions.Move: if (mMotionHighlightView != null) { mMotionHighlightView.HandleMotion(ev.GetX(), ev.GetY(), mLastCropHandle.Postion); } break; } return true; } public bool OnTouchEvent(MotionEvent ev, bool IsOldMethod) // TODO: was override { CropImageActivity cropImageActivity = (CropImageActivity)context; if (cropImageActivity.Saving) { return false; } switch (ev.Action) { case MotionEventActions.Down: for (int i = 0; i < hightlightViews.Count; i++) { HighlightView hv = hightlightViews[i]; var edge = hv.GetHit(ev.GetX(), ev.GetY()); // TODO: Review and uncomment when we fix ontouchevent //if (edge != global::com.bytewild.imaging.cropper.HighlightView.HitPosition.None) //{ // motionEdge = edge; // mMotionHighlightView = hv; // mLastX = ev.GetX(); // mLastY = ev.GetY(); // mMotionHighlightView.Mode = // (edge == global::com.bytewild.imaging.cropper.HighlightView.HitPosition.Move) // ? HighlightView.ModifyMode.Move // : HighlightView.ModifyMode.Grow; // break; //} } break; case MotionEventActions.Up: if (mMotionHighlightView != null) { centerBasedOnHighlightView(mMotionHighlightView); mMotionHighlightView.Mode = HighlightView.ModifyMode.None; } mMotionHighlightView = null; break; case MotionEventActions.Move: if (mMotionHighlightView != null) { mMotionHighlightView.HandleMotion(motionEdge, ev.GetX() - mLastX, ev.GetY() - mLastY); mLastX = ev.GetX(); mLastY = ev.GetY(); if (true) { // This section of code is optional. It has some user // benefit in that moving the crop rectangle against // the edge of the screen causes scrolling but it means // that the crop rectangle is no longer fixed under // the user's finger. ensureVisible(mMotionHighlightView); } } break; } switch (ev.Action) { case MotionEventActions.Up: Center(true, true); break; case MotionEventActions.Move: // if we're not zoomed then there's no point in even allowing // the user to move the image around. This call to center puts // it back to the normalized location (with false meaning don't // animate). if (GetScale() == 1F) { Center(true, true); } break; } return true; } #endregion #region Private helpers // Pan the displayed image to make sure the cropping rectangle is visible. private void ensureVisible(HighlightView hv) { Rect r = hv.DrawRect; int panDeltaX1 = Math.Max(0, IvLeft - r.Left); int panDeltaX2 = Math.Min(0, IvRight - r.Right); int panDeltaY1 = Math.Max(0, IvTop - r.Top); int panDeltaY2 = Math.Min(0, IvBottom - r.Bottom); int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2; int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2; if (panDeltaX != 0 || panDeltaY != 0) { PanBy(panDeltaX, panDeltaY); } } // If the cropping rectangle's size changed significantly, change the // view's center and scale according to the cropping rectangle. private void centerBasedOnHighlightView(HighlightView hv) { Rect drawRect = hv.DrawRect; float width = drawRect.Width(); float height = drawRect.Height(); float thisWidth = Width; float thisHeight = Height; float z1 = thisWidth / width * .6F; float z2 = thisHeight / height * .6F; float zoom = Math.Min(z1, z2); zoom = zoom * this.GetScale(); zoom = Math.Max(1F, zoom); if ((Math.Abs(zoom - GetScale()) / zoom) > .1) { float[] coordinates = new float[] { hv.CropRect.CenterX(), hv.CropRect.CenterY() }; ImageMatrix.MapPoints(coordinates); ZoomTo(zoom, coordinates[0], coordinates[1], 300F); } ensureVisible(hv); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Rceptor.Core.ServiceClient; using Rceptor.Core.ServiceProxy.Provider; namespace Rceptor.Core.ServiceProxy { public class OperationDescription : IRequestContextProvider, IRouteAddressBuilder { #region Properties /// <summary> /// Base of operation method /// </summary> public MethodInfo MethodInfo { get; set; } /// <summary> /// Service contract context /// </summary> public ContractDescription ServiceContract { get; set; } /// <summary> /// Original route template /// </summary> public string Route => ActionBinding?.RouteTemplate; /// <summary> /// Method name or action name /// </summary> public string Name { get; set; } /// <summary> /// Operation method information, route template, route entries, http methods etc.. /// </summary> public ApiActionBinding ActionBinding { get; set; } #endregion #region IRouteAddressBuilder Members public IReadOnlyList<KeyValuePair<string, RouteDataInformation>> GetRouteDataInformation(params object[] callArguments) { var targetMethod = MethodInfo; if (targetMethod == null) throw new ArgumentNullException(nameof(targetMethod)); var routeInfos = new List<KeyValuePair<string, RouteDataInformation>>(); var arguments = callArguments ?? new object[] { }; // Check method parameter count and method call argument var parameterCount = targetMethod.GetParameters().Length; if (parameterCount != arguments.Length) throw new ArgumentException("Invoked method has different arguments. Check named arguments of method."); var methodParametersInfo = (from p in targetMethod.GetParameters() select new { p.Name, p.Position, Value = arguments[p.Position], p.DefaultValue, p.HasDefaultValue }).ToArray(); var routeEntries = ActionBinding.ActionParameters.OrderBy(r => r.Order); foreach (var routeEntry in routeEntries) { // Dont't use request content data as route parameters. if (routeEntry.InBody) continue; var routeInfo = new RouteDataInformation(routeEntry); if (!routeEntry.IsVariable) { routeInfo.SetRouteData(routeEntry.Name); } else { var parameterInfo = methodParametersInfo.FirstOrDefault(f => f.Name == routeEntry.Name); if (parameterInfo == null) continue; routeInfo.SetRouteData(parameterInfo.Value ?? parameterInfo.DefaultValue); if (!routeInfo.HasValue) { // If not pass arguments for parameter, set argument from route entry default value. if (routeEntry.InTemplate && routeEntry.DefaultValue != null) { routeInfo.SetRouteData(routeEntry.DefaultValue); } } } routeInfos.Add(new KeyValuePair<string, RouteDataInformation>(routeEntry.Name, routeInfo)); } return routeInfos; } public string BuildActionRoute(params object[] callArguments) { return BuildActionRouteAddress(callArguments ?? new object[] { }); } public string BuildActionRouteWithContract(params object[] callArguments) { return CompleteActionUri(callArguments ?? new object[] { }); } #endregion #region IRequestContextProvider Members public RestRequestContext GetRequestContext(params object[] callArguments) { var bindingContext = ServiceContract.ServiceBindingContext; var context = new RestRequestContext { ApiMethods = ActionBinding.AcceptHttpMethods, ActionUri = CompleteActionUri(callArguments), ContentData = ActionBinding.ActionParameters.Where(p => p.InBody) .ToDictionary(r => r.Name, r => callArguments[r.Order]), MediaTypes = bindingContext.SupportedMediaTypes, Formatters = bindingContext.Formatters }; return context; } #endregion #region Helpers private string CompleteActionUri(object[] arguments) { var routePrefix = ServiceContract.RoutePrefix; var actionRoute = BuildActionRouteAddress(arguments); var serviceUri = ""; if (!string.IsNullOrEmpty(routePrefix) && !string.IsNullOrEmpty(actionRoute)) serviceUri = $"{routePrefix}/{actionRoute}"; else if (string.IsNullOrEmpty(routePrefix)) serviceUri = $"{actionRoute}"; else if (string.IsNullOrEmpty(actionRoute)) serviceUri = $"{routePrefix}"; return serviceUri; } private string BuildActionRouteAddress(object[] arguments) { var routeInfos = GetRouteDataInformation(arguments); if (!routeInfos.Any()) { // If not provided routes, set action method name as default route. return ActionBinding.ActionRouteName; } var inRouteAddressList = new List<string>(); var querySegmentAddressList = new List<RouteDataInformation>(); foreach (var info in routeInfos.OrderBy(o => o.Value.RouteEntry.Order)) { if (!info.Value.HasValue) continue; var routeInfo = info.Value; if (!routeInfo.IsQuerySegment) { inRouteAddressList.Add(routeInfo.RouteData.ToString()); } else { querySegmentAddressList.Add(routeInfo); } } var routedAddress = ""; var queryAddress = ""; if (inRouteAddressList.Any()) routedAddress = inRouteAddressList.Aggregate((p, pp) => $"{p}/{pp}"); if (querySegmentAddressList.Any()) queryAddress = querySegmentAddressList .Select(item => item.IsComplexType // If route data is complex type, complete addrfess from only serialized route data. ? $"{item.RouteData}" // If route data is not complex type, set query address from name and value. : $"{item.Name}={item.RouteData}") .Aggregate((f, s) => $"{f}&{s}"); string completeActionRouteAddress = null; // Merge routed and query segments address. if (!string.IsNullOrEmpty(routedAddress)) { if (!string.IsNullOrEmpty(queryAddress)) { completeActionRouteAddress = $"{routedAddress}?{queryAddress}"; } else { completeActionRouteAddress = $"{routedAddress}"; } } else if (!string.IsNullOrEmpty(queryAddress)) { completeActionRouteAddress = $"?{queryAddress}"; } return completeActionRouteAddress; } #endregion } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace tk2dEditor.SpriteAnimationEditor { public class ClipEditor { // Accessors tk2dSpriteAnimationClip clip = null; public tk2dSpriteAnimationClip Clip { get { return clip; } set { SetClip(value); } } public EditorWindow hostEditorWindow = null; public void InitForNewClip() { selectClipNameField = true; timelineEditor.CurrentState.selectedFrame = 0; } bool selectClipNameField = false; // Locals int minInspectorWidth = 170; int inspectorWidth { get { return tk2dPreferences.inst.animInspectorWidth; } set { tk2dPreferences.inst.animInspectorWidth = Mathf.Max(value, minInspectorWidth); } } tk2dSpriteAnimationPreview preview = null; TimelineEditor timelineEditor = new TimelineEditor(); // Events public delegate void ClipEventDelegate(tk2dSpriteAnimationClip clip, int data); public event ClipEventDelegate clipNameChangedEvent; public event ClipEventDelegate clipDeletedEvent; public event ClipEventDelegate clipSelectionChangedEvent; void OnClipNameChanged() { if (clipNameChangedEvent != null) clipNameChangedEvent(clip, 0); } void OnClipDeleted() { if (clipDeletedEvent != null) clipDeletedEvent(clip, 0); } bool OnClipSelectionChanged(int direction) { if (clipSelectionChangedEvent != null) clipSelectionChangedEvent(clip, direction); return clipSelectionChangedEvent != null; } void Repaint() { if (hostEditorWindow != null) { hostEditorWindow.Repaint(); } else { HandleUtility.Repaint(); } } // Sprite changed callback // Create an instance - only ever use the instance through the property void SpriteChangedCallbackImpl(tk2dSpriteCollectionData spriteCollection, int spriteId, object data) { FrameGroup fg = data as FrameGroup; // Ensure the user hasn't switched sprite collection if (fg != null && frameGroups.IndexOf(fg) != -1) { fg.spriteCollection = spriteCollection; fg.spriteId = spriteId; foreach (tk2dSpriteAnimationFrame frame in fg.frames) { frame.spriteCollection = spriteCollection; frame.spriteId = spriteId; } RecalculateFrames(); Repaint(); } } tk2dSpriteGuiUtility.SpriteChangedCallback _spriteChangedCallbackInstance = null; tk2dSpriteGuiUtility.SpriteChangedCallback spriteChangedCallbackInstance { get { if (_spriteChangedCallbackInstance == null) { _spriteChangedCallbackInstance = new tk2dSpriteGuiUtility.SpriteChangedCallback( SpriteChangedCallbackImpl ); } return _spriteChangedCallbackInstance; } } // Editor operations public tk2dEditor.SpriteAnimationEditor.AnimOperator[] animOps = new tk2dEditor.SpriteAnimationEditor.AnimOperator[0]; // Construction/Destruction public void Destroy() { if (preview != null) preview.Destroy(); if (_animator != null) Object.DestroyImmediate(_animator.gameObject); } // Frame groups public class FrameGroup { public tk2dSpriteCollectionData spriteCollection; public int spriteId; public List<tk2dSpriteAnimationFrame> frames = new List<tk2dSpriteAnimationFrame>(); public int startFrame = 0; // this is a cache value used during the draw loop public bool SetFrameCount(int targetFrameCount) { bool changed = false; if (frames.Count > targetFrameCount) { frames.RemoveRange(targetFrameCount, frames.Count - targetFrameCount); changed = true; } while (frames.Count < targetFrameCount) { tk2dSpriteAnimationFrame f = new tk2dSpriteAnimationFrame(); f.spriteCollection = spriteCollection; f.spriteId = spriteId; frames.Add(f); changed = true; } return changed; } public List<tk2dSpriteAnimationFrame> DuplicateFrames(List<tk2dSpriteAnimationFrame> source) { List<tk2dSpriteAnimationFrame> dest = new List<tk2dSpriteAnimationFrame>(); foreach (tk2dSpriteAnimationFrame f in source) { tk2dSpriteAnimationFrame q = new tk2dSpriteAnimationFrame(); q.CopyFrom(f); dest.Add(q); } return dest; } public void Update() { foreach (tk2dSpriteAnimationFrame frame in frames) { frame.spriteCollection = spriteCollection; frame.spriteId = spriteId; } } } List<FrameGroup> frameGroups = new List<FrameGroup>(); // Sprite animator tk2dSpriteAnimator _animator = null; void InitAnimator() { if (_animator == null) { GameObject go = new GameObject("@SpriteAnimator"); go.hideFlags = HideFlags.HideAndDontSave; #if UNITY_3_5 go.active = false; #else go.SetActive(false); #endif go.AddComponent<tk2dSprite>(); _animator = go.AddComponent<tk2dSpriteAnimator>(); } } tk2dSpriteAnimator Animator { get { InitAnimator(); return _animator; } } bool CheckValidClip(tk2dSpriteAnimationClip clip) { bool nullCollectionFound = false; bool invalidSpriteIdFound = false; for (int i = 0; i < clip.frames.Length; ++i) { tk2dSpriteAnimationFrame frame = clip.frames[i]; if (frame.spriteCollection == null) { nullCollectionFound = true; } else { if (!frame.spriteCollection.IsValidSpriteId(frame.spriteId)) { if (frame.spriteCollection.FirstValidDefinitionIndex == -1) { nullCollectionFound = true; } else { invalidSpriteIdFound = true; } } } } if (nullCollectionFound) { EditorUtility.DisplayDialog("Invalid sprite collection found in clip.", "An invalid sprite collection has been found in the selected clip. Please correct this in the inspector.", "Ok"); return false; } if (invalidSpriteIdFound) { if (EditorUtility.DisplayDialog("Invalid sprite found in clip.", "An invalid sprite has been found in the selected clip. Has the sprite been deleted from the collection?\n\nDo you wish to replace this with a valid sprite from the collection?\n\nThis may not be correct, but you will be able to edit the clip after this.", "Yes", "No")) { for (int i = 0; i < clip.frames.Length; ++i) { tk2dSpriteAnimationFrame frame = clip.frames[i]; if (!frame.spriteCollection.IsValidSpriteId(frame.spriteId)) { frame.spriteId = frame.spriteCollection.FirstValidDefinitionIndex; } } return true; } else { return false; } } return true; } // Internal set clip, reset all void SetClip(tk2dSpriteAnimationClip clip) { if (this.clip != clip) { // reset stuff this.clip = clip; timelineEditor.Reset(); if (!repeatPlayAnimation) playAnimation = false; this.Animator.Stop(); // build frame groups if (clip != null) { if (CheckValidClip(clip)) { // check if clip is valid? frameGroups.Clear(); tk2dSpriteCollectionData lastSc = null; int lastSpriteId = -1; FrameGroup frameGroup = null; for (int i = 0; i < clip.frames.Length; ++i) { tk2dSpriteAnimationFrame f = clip.frames[i]; if (f.spriteCollection != lastSc || f.spriteId != lastSpriteId) { if (frameGroup != null) frameGroups.Add(frameGroup); frameGroup = new FrameGroup(); frameGroup.spriteCollection = f.spriteCollection; frameGroup.spriteId = f.spriteId; } lastSc = f.spriteCollection; lastSpriteId = f.spriteId; frameGroup.frames.Add(f); } if (frameGroup != null) frameGroups.Add(frameGroup); // Select first frame group if (frameGroups.Count > 0) { timelineEditor.CurrentState.selectedFrame = 0; } } } } } double previousTimeStamp = -1.0f; float deltaTime = 0.0f; void DrawPreview() { GUILayout.BeginVertical(GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); Rect r = GUILayoutUtility.GetRect(1, 1, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); // get frame from frame group if (playAnimation) { preview.Draw(r, Animator.Sprite.GetCurrentSpriteDef()); } else { if (timelineEditor.CurrentState.selectedFrame == -1) { preview.Draw(r, null); } else { int frame = timelineEditor.CurrentState.selectedFrame; if (frameGroups != null && frame < frameGroups.Count) { FrameGroup fg = frameGroups[frame]; tk2dSpriteCollectionData sc = fg.spriteCollection.inst; preview.Draw(r, sc.spriteDefinitions[fg.spriteId]); } } } GUILayout.EndVertical(); } void DrawClipInspector() { GUILayout.BeginHorizontal(); GUILayout.Label("Clip", EditorStyles.largeLabel); if (GUILayout.Button("Delete", GUILayout.Width(46)) && EditorUtility.DisplayDialog("Delete clip", "Are you sure you want to delete the selected clip?", "Yes", "No")) { OnClipDeleted(); } GUILayout.EndHorizontal(); GUI.SetNextControlName("tk2dAnimName"); string changedName = EditorGUILayout.TextField("Name", clip.name).Trim(); if (selectClipNameField) { GUI.FocusControl("tk2dAnimName"); selectClipNameField = false; } if (changedName != clip.name && changedName.Length > 0) { clip.name = changedName; OnClipNameChanged(); } EditorGUILayout.IntField("Frames", clip.frames.Length); float fps = EditorGUILayout.FloatField("Frame rate", clip.fps); if (fps > 0) clip.fps = fps; float clipTime = clip.frames.Length / fps; float newClipTime = EditorGUILayout.FloatField("Clip time", clipTime); if (newClipTime > 0 && newClipTime != clipTime) clip.fps = clip.frames.Length / newClipTime; tk2dSpriteAnimationClip.WrapMode newWrapMode = (tk2dSpriteAnimationClip.WrapMode)EditorGUILayout.EnumPopup("Wrap Mode", clip.wrapMode); if (clip.wrapMode == tk2dSpriteAnimationClip.WrapMode.LoopSection) { clip.loopStart = EditorGUILayout.IntField("Loop Start", clip.loopStart); clip.loopStart = Mathf.Clamp(clip.loopStart, 0, clip.frames.Length - 1); } if (newWrapMode != clip.wrapMode) { if (newWrapMode == tk2dSpriteAnimationClip.WrapMode.Single && clip.frames.Length > 1) { // Will we be truncating the animation? if (EditorUtility.DisplayDialog("Wrap mode -> Single", "This will truncate your clip to a single frame. Do you want to continue?", "Yes", "No")) { clip.wrapMode = newWrapMode; frameGroups.RemoveRange(1, frameGroups.Count - 1); frameGroups[0].SetFrameCount(1); ClipEditor.RecalculateFrames(clip, frameGroups); } } else { clip.wrapMode = newWrapMode; } } // Tools GUILayout.Space(8); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); GUILayout.BeginVertical(); bool changed = false; foreach (tk2dEditor.SpriteAnimationEditor.AnimOperator animOp in animOps) { changed = animOp.OnClipInspectorGUI(clip, frameGroups, timelineEditor.CurrentState); if ((animOp.AnimEditOperations & tk2dEditor.SpriteAnimationEditor.AnimEditOperations.ClipContentChanged) != tk2dEditor.SpriteAnimationEditor.AnimEditOperations.None) { RecalculateFrames(); changed = true; } if ((animOp.AnimEditOperations & tk2dEditor.SpriteAnimationEditor.AnimEditOperations.ClipNameChanged) != tk2dEditor.SpriteAnimationEditor.AnimEditOperations.None) { OnClipNameChanged(); changed = true; } } if (changed) Repaint(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.Space(8); } void DrawFrameInspector() { GUILayout.Label("Frame", EditorStyles.largeLabel, GUILayout.ExpandWidth(true)); FrameGroup fg = frameGroups[timelineEditor.CurrentState.selectedFrame]; tk2dSpriteGuiUtility.SpriteSelector( fg.spriteCollection, fg.spriteId, spriteChangedCallbackInstance, fg ); int numFrames = EditorGUILayout.IntField("Frames", fg.frames.Count); if (numFrames != fg.frames.Count && numFrames > 0) { if (fg.SetFrameCount(numFrames)) { RecalculateFrames(); Repaint(); } } float time0 = fg.frames.Count / clip.fps; float time = EditorGUILayout.FloatField("Time", time0); if (time != time0) { int frameCount = Mathf.Max(1, (int)Mathf.Ceil(time * clip.fps)); if (fg.SetFrameCount(frameCount)) { RecalculateFrames(); Repaint(); } } // Tools GUILayout.Space(8); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); GUILayout.BeginVertical(); bool changed = false; foreach (tk2dEditor.SpriteAnimationEditor.AnimOperator animOp in animOps) { changed = animOp.OnFrameGroupInspectorGUI(clip, frameGroups, timelineEditor.CurrentState); if ((animOp.AnimEditOperations & tk2dEditor.SpriteAnimationEditor.AnimEditOperations.ClipContentChanged) != tk2dEditor.SpriteAnimationEditor.AnimEditOperations.None) { RecalculateFrames(); changed = true; } } if (changed) Repaint(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); } bool repeatPlayAnimation = false; const float repeatPlayWaitTimeConst = 1.0f; float repeatPlayWaitTime = 0; bool playAnimation = false; void TogglePlayAnimation() { if (playAnimation) { if (Animator != null) Animator.Stop(); playAnimation = false; } else { PlayAnimation(); } } void PlayAnimation() { if (Clip != null && Clip.frames.Length > 0) { playAnimation = true; previousTimeStamp = EditorApplication.timeSinceStartup; // reset time to avoid huge delta time repeatPlayWaitTime = repeatPlayWaitTimeConst; Animator.PlayFrom(Clip, 0); Repaint(); } } void DrawTransportToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); if (Event.current.type == EventType.Repaint) { if (playAnimation && !Animator.Playing) { if (repeatPlayAnimation || clip.wrapMode == tk2dSpriteAnimationClip.WrapMode.Single) { if (repeatPlayWaitTime > 0.0f) { repeatPlayWaitTime -= deltaTime; Repaint(); } else { Animator.PlayFrom(Clip, 0); repeatPlayWaitTime = repeatPlayWaitTimeConst; Repaint(); } } else { playAnimation = false; } } } GUIContent stopContent = new GUIContent("Stop", "Stop playing the current animation (Enter)"); GUIContent startContent = new GUIContent("Play", "Start playing the current animation (Enter)"); GUIContent playLabel = playAnimation ? stopContent : startContent; bool newPlayAnimation = GUILayout.Toggle(playAnimation, playLabel, EditorStyles.toolbarButton, GUILayout.Width(35)); if (newPlayAnimation != playAnimation) { if (newPlayAnimation == true) { PlayAnimation(); } else { Animator.Stop(); Repaint(); } playAnimation = newPlayAnimation; } repeatPlayAnimation = GUILayout.Toggle(repeatPlayAnimation, "Repeat", EditorStyles.toolbarButton); GUILayout.FlexibleSpace(); tk2dPreferences.inst.gridType = (tk2dGrid.Type)EditorGUILayout.EnumPopup(tk2dPreferences.inst.gridType, EditorStyles.toolbarDropDown, GUILayout.Width(95)); GUILayout.EndHorizontal(); } void DrawTriggerInspector() { GUILayout.Label("Trigger", EditorStyles.largeLabel, GUILayout.ExpandWidth(true)); tk2dSpriteAnimationFrame frame = clip.frames[timelineEditor.CurrentState.selectedTrigger]; EditorGUILayout.LabelField("Frame", timelineEditor.CurrentState.selectedTrigger.ToString()); frame.eventInfo = EditorGUILayout.TextField("Info", frame.eventInfo); frame.eventFloat = EditorGUILayout.FloatField("Float", frame.eventFloat); frame.eventInt = EditorGUILayout.IntField("Int", frame.eventInt); GUILayout.Space(8); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(" "); GUILayout.BeginVertical(); if (GUILayout.Button("Delete", EditorStyles.miniButton)) { clip.frames[timelineEditor.CurrentState.selectedTrigger].ClearTrigger(); timelineEditor.CurrentState.Reset(); Repaint(); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } Vector2 inspectorScrollbar = Vector2.zero; void DrawInspector() { tk2dGuiUtility.LookLikeControls(80.0f, 40.0f); inspectorScrollbar = GUILayout.BeginScrollView(inspectorScrollbar, GUILayout.ExpandHeight(true), GUILayout.Width(inspectorWidth)); // Heading GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorHeaderBG, GUILayout.ExpandWidth(true)); DrawClipInspector(); GUILayout.EndVertical(); DrawTransportToolbar(); // Contents GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorBG, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); if (timelineEditor.CurrentState.selectedFrame != -1) DrawFrameInspector(); if (timelineEditor.CurrentState.selectedTrigger != -1) DrawTriggerInspector(); GUILayout.EndVertical(); GUILayout.EndScrollView(); Rect viewRect = GUILayoutUtility.GetLastRect(); // Resize handle inspectorWidth -= (int)tk2dGuiUtility.DragableHandle(4819518, viewRect, 0, tk2dGuiUtility.DragDirection.Horizontal); } public static void RecalculateFrames(tk2dSpriteAnimationClip clip, List<FrameGroup> frameGroups) { List<tk2dSpriteAnimationFrame> frames = new List<tk2dSpriteAnimationFrame>(); foreach (var v in frameGroups) frames.AddRange(v.frames); clip.frames = frames.ToArray(); } // Internal convenience function void RecalculateFrames() { ClipEditor.RecalculateFrames(clip, frameGroups); } void HandleKeyboardShortcuts() { Event ev = Event.current; if (ev.type == EventType.KeyDown && GUIUtility.keyboardControl == 0) { switch (ev.keyCode) { case KeyCode.UpArrow: if (OnClipSelectionChanged(-1)) ev.Use(); break; case KeyCode.DownArrow: if (OnClipSelectionChanged(1)) ev.Use(); break; case KeyCode.Return: TogglePlayAnimation(); ev.Use(); break; case KeyCode.F: if (preview != null) preview.ResetTransform(); ev.Use(); break; } } } public void Draw(int windowWidth) { if (clip == null) return; if (preview == null) preview = new tk2dSpriteAnimationPreview(); // Update if (Event.current.type == EventType.Repaint) { double t = EditorApplication.timeSinceStartup; if (previousTimeStamp < 0) previousTimeStamp = t; deltaTime = (float)(t - previousTimeStamp); previousTimeStamp = t; // Update sprite if (Animator.Playing) { Animator.ClipFps = clip.fps; Animator.UpdateAnimation(deltaTime); Repaint(); // refresh } } // Idle key handling if (GUIUtility.keyboardControl == 0) HandleKeyboardShortcuts(); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); DrawPreview(); DrawInspector(); GUILayout.EndHorizontal(); float clipTimeMarker = -1.0f; if (playAnimation) { float clipTime = Animator.Playing ? Animator.EditorClipTime : 0.0f; clipTimeMarker = clipTime; } timelineEditor.Draw(windowWidth, clip, frameGroups, clipTimeMarker); GUILayout.EndVertical(); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ProbabilisticDataStructures; using System.Text; using System.Collections.Generic; namespace TestProbabilisticDataStructures { [TestClass] public class TestBloomFilter64 { private static byte[] A_BYTES = Encoding.ASCII.GetBytes("a"); private static byte[] B_BYTES = Encoding.ASCII.GetBytes("b"); private static byte[] C_BYTES = Encoding.ASCII.GetBytes("c"); private static byte[] X_BYTES = Encoding.ASCII.GetBytes("x"); /// <summary> /// Ensures that Capacity() returns the number of bits, m, in the Bloom filter. /// </summary> [TestMethod] public void TestBloomCapacity() { var f = new BloomFilter64(100, 0.1); var capacity = f.Capacity(); Assert.AreEqual(480u, capacity); } /// <summary> /// Ensures that K() returns the number of hash functions in the Bloom Filter. /// </summary> [TestMethod] public void TestBloom64K() { var f = new BloomFilter64(100, 0.1); var k = f.K(); Assert.AreEqual(4u, k); } /// <summary> /// Ensures that Count returns the number of items added to the filter. /// </summary> [TestMethod] public void TestBloom64Count() { var f = new BloomFilter64(100, 0.1); for (uint i = 0; i < 10; i++) { f.Add(Encoding.ASCII.GetBytes(i.ToString())); } var count = f.Count(); Assert.AreEqual(10u, count); } /// <summary> /// Ensures that EstimatedFillRatio returns the correct approximation. /// </summary> [TestMethod] public void TestBloom64EstimatedFillRatio() { var f = new BloomFilter64(100, 0.5); for (uint i = 0; i < 100; i++) { f.Add(Encoding.ASCII.GetBytes(i.ToString())); } var ratio = f.EstimatedFillRatio(); if (ratio > 0.5) { Assert.Fail("Expected less than or equal to 0.5, got {0}", ratio); } } /// <summary> /// Ensures that FillRatio returns the ratio of set bits. /// </summary> [TestMethod] public void TestBloom64FillRatio() { var f = new BloomFilter64(100, 0.1); f.Add(A_BYTES); f.Add(B_BYTES); f.Add(C_BYTES); var ratio = f.FillRatio(); Assert.AreEqual(0.025, ratio); } /// <summary> /// Ensures that Test, Add, and TestAndAdd behave correctly. /// </summary> [TestMethod] public void TestBloom64TestAndAdd() { var f = new BloomFilter64(100, 0.01); // 'a' is not in the filter. if (f.Test(A_BYTES)) { Assert.Fail("'a' should not be a member"); } var addedF = f.Add(A_BYTES); Assert.AreSame(f, addedF, "Returned BloomFilter64 should be the same instance"); // 'a' is now in the filter. if (!f.Test(A_BYTES)) { Assert.Fail("'a' should be a member"); } // 'a' is still in the filter. if (!f.TestAndAdd(A_BYTES)) { Assert.Fail("'a' should be a member"); } // 'b' is not in the filter. if (f.TestAndAdd(B_BYTES)) { Assert.Fail("'b' should not be a member"); } // 'a' is still in the filter. if (!f.Test(A_BYTES)) { Assert.Fail("'a' should be a member"); } // 'b' is now in the filter. if (!f.Test(B_BYTES)) { Assert.Fail("'b' should be a member"); } // 'c' is not in the filter. if (f.Test(C_BYTES)) { Assert.Fail("'c' should not be a member"); } for (int i = 0; i < 1000000; i++) { f.TestAndAdd(Encoding.ASCII.GetBytes(i.ToString())); } // 'x' should be a false positive. if (!f.Test(X_BYTES)) { Assert.Fail("'x' should be a member"); } } /// <summary> /// Ensures that Reset sets every bit to zero. /// </summary> [TestMethod] public void TestBloom64Reset() { var f = new BloomFilter64(100, 0.1); for (int i = 0; i < 1000; i++) { f.Add(Encoding.ASCII.GetBytes(i.ToString())); } var resetF = f.Reset(); Assert.AreSame(f, resetF, "Returned BloomFilter64 should be the same instance"); for (uint i = 0; i < f.Buckets.count; i++) { if (f.Buckets.Get(i) != 0) { Assert.Fail("Expected all bits to be unset"); } } } } [TestClass] public class BenchmarkBloomFilter64 { private BloomFilter64 f; private int n; private byte[][] data; [TestInitialize()] public void Testinitialize() { n = 100000; f = new BloomFilter64(100000, 0.1); data = new byte[n][]; for (int i = 0; i < n; i++) { data[i] = Encoding.ASCII.GetBytes(i.ToString()); } } [TestCleanup()] public void TestCleanup() { f = null; n = 0; data = null; } [TestMethod] public void BenchmarkBloom64Add() { for (int i = 0; i < n; i++) { f.Add(data[i]); } } [TestMethod] public void BenchmarkBloom64Test() { for (int i = 0; i < n; i++) { f.Test(data[i]); } } [TestMethod] public void BenchmarkBloom64TestAndAdd() { for (int i = 0; i < n; i++) { f.TestAndAdd(data[i]); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineScaleSetUpdateDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "VirtualMachineScaleSetUpdate"; pParameters.ParameterType = typeof(VirtualMachineScaleSetUpdate); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VirtualMachineScaleSetUpdate", pParameters); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineScaleSetUpdateMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]); VirtualMachineScaleSetUpdate parameters = (VirtualMachineScaleSetUpdate)ParseParameter(invokeMethodInputParameters[2]); VirtualMachineScaleSet parametersOrg = (VirtualMachineScaleSet)ParseParameter(invokeMethodInputParameters[3]); var result = (parameters == null) ? VirtualMachineScaleSetsClient.CreateOrUpdate(resourceGroupName, vmScaleSetName, parametersOrg) : VirtualMachineScaleSetsClient.Update(resourceGroupName, vmScaleSetName, parameters); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineScaleSetUpdateParameters() { string resourceGroupName = string.Empty; string vmScaleSetName = string.Empty; VirtualMachineScaleSetUpdate parameters = new VirtualMachineScaleSetUpdate(); return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMScaleSetName", "Parameters" }, new object[] { resourceGroupName, vmScaleSetName, parameters }); } } [Cmdlet(VerbsData.Update, "AzureRmVmss", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSVirtualMachineScaleSet))] public partial class UpdateAzureRmVmss : ComputeAutomationBaseCmdlet { protected override void ProcessRecord() { ExecuteClientAction(() => { if (ShouldProcess(this.VMScaleSetName, VerbsData.Update)) { string resourceGroupName = this.ResourceGroupName; string vmScaleSetName = this.VMScaleSetName; if (this.VirtualMachineScaleSet == null) { BuildPatchObject(); } else { BuildPutObject(); } VirtualMachineScaleSetUpdate parametersupdate = this.VirtualMachineScaleSetUpdate; VirtualMachineScaleSet parameters = new VirtualMachineScaleSet(); ComputeAutomationAutoMapperProfile.Mapper.Map<PSVirtualMachineScaleSet, VirtualMachineScaleSet>(this.VirtualMachineScaleSet, parameters); var result = (this.VirtualMachineScaleSetUpdate == null) ? VirtualMachineScaleSetsClient.CreateOrUpdate(resourceGroupName, vmScaleSetName, parameters) : VirtualMachineScaleSetsClient.Update(resourceGroupName, vmScaleSetName, parametersupdate); var psObject = new PSVirtualMachineScaleSet(); ComputeAutomationAutoMapperProfile.Mapper.Map<VirtualMachineScaleSet, PSVirtualMachineScaleSet>(result, psObject); WriteObject(psObject); } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Alias("Name")] [AllowNull] public string VMScaleSetName { get; set; } public VirtualMachineScaleSetUpdate VirtualMachineScaleSetUpdate { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = false, ValueFromPipeline = true)] [AllowNull] public PSVirtualMachineScaleSet VirtualMachineScaleSet { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string ImageReferenceSku { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public bool? EnableAutomaticUpdate { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public StorageAccountTypes? ManagedDiskStorageAccountType { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string PlanPublisher { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public bool? ProvisionVMAgent { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public bool? BootDiagnosticsEnabled { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public bool? Overprovision { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public int? MaxBatchInstancePercent { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string TimeZone { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string BootDiagnosticsStorageUri { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public bool? AutomaticOSUpgrade { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public bool? SinglePlacementGroup { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string CustomData { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public UpgradeMode? UpgradePolicyMode { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string ImageReferenceId { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public bool? DisablePasswordAuthentication { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public Hashtable Tag { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string PlanName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public int? MaxUnhealthyUpgradedInstancePercent { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string ImageReferencePublisher { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string PlanProduct { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string ImageUri { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string SkuTier { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string[] VhdContainer { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string LicenseType { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public ResourceIdentityType? IdentityType { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string SkuName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string PlanPromotionCode { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public int? MaxUnhealthyInstancePercent { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public int? SkuCapacity { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string ImageReferenceOffer { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string PauseTimeBetweenBatches { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public CachingTypes? OsDiskCaching { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [ValidateNotNullOrEmpty] public string ImageReferenceVersion { get; set; } private void BuildPatchObject() { if (this.ImageReferenceSku != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Sku = this.ImageReferenceSku; } if (this.EnableAutomaticUpdate != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = this.EnableAutomaticUpdate; } if (this.ManagedDiskStorageAccountType != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetManagedDiskParameters(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.StorageAccountType = this.ManagedDiskStorageAccountType; } if (this.PlanPublisher != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.Plan == null) { this.VirtualMachineScaleSetUpdate.Plan = new Microsoft.Azure.Management.Compute.Models.Plan(); } this.VirtualMachineScaleSetUpdate.Plan.Publisher = this.PlanPublisher; } if (this.ProvisionVMAgent != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration.ProvisionVMAgent = this.ProvisionVMAgent; } if (this.BootDiagnosticsEnabled != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new Microsoft.Azure.Management.Compute.Models.BootDiagnostics(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.Enabled = this.BootDiagnosticsEnabled; } if (this.Overprovision != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } this.VirtualMachineScaleSetUpdate.Overprovision = this.Overprovision; } if (this.MaxBatchInstancePercent != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy(); } this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy.MaxBatchInstancePercent = this.MaxBatchInstancePercent; } if (this.TimeZone != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration.TimeZone = this.TimeZone; } if (this.BootDiagnosticsStorageUri != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new Microsoft.Azure.Management.Compute.Models.BootDiagnostics(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.StorageUri = this.BootDiagnosticsStorageUri; } if (this.AutomaticOSUpgrade != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } this.VirtualMachineScaleSetUpdate.UpgradePolicy.AutomaticOSUpgrade = this.AutomaticOSUpgrade; } if (this.SinglePlacementGroup != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } this.VirtualMachineScaleSetUpdate.SinglePlacementGroup = this.SinglePlacementGroup; } if (this.CustomData != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.CustomData = this.CustomData; } if (this.UpgradePolicyMode != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } this.VirtualMachineScaleSetUpdate.UpgradePolicy.Mode = this.UpgradePolicyMode; } if (this.ImageReferenceId != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Id = this.ImageReferenceId; } if (this.DisablePasswordAuthentication != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.LinuxConfiguration == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.LinuxConfiguration = new Microsoft.Azure.Management.Compute.Models.LinuxConfiguration(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.LinuxConfiguration.DisablePasswordAuthentication = this.DisablePasswordAuthentication; } if (this.Tag != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } this.VirtualMachineScaleSetUpdate.Tags = this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value); } if (this.PlanName != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.Plan == null) { this.VirtualMachineScaleSetUpdate.Plan = new Microsoft.Azure.Management.Compute.Models.Plan(); } this.VirtualMachineScaleSetUpdate.Plan.Name = this.PlanName; } if (this.MaxUnhealthyUpgradedInstancePercent != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy(); } this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyUpgradedInstancePercent = this.MaxUnhealthyUpgradedInstancePercent; } if (this.ImageReferencePublisher != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Publisher = this.ImageReferencePublisher; } if (this.PlanProduct != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.Plan == null) { this.VirtualMachineScaleSetUpdate.Plan = new Microsoft.Azure.Management.Compute.Models.Plan(); } this.VirtualMachineScaleSetUpdate.Plan.Product = this.PlanProduct; } if (this.ImageUri != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.Image == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.Image = new Microsoft.Azure.Management.Compute.Models.VirtualHardDisk(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri = this.ImageUri; } if (this.SkuTier != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.Sku == null) { this.VirtualMachineScaleSetUpdate.Sku = new Microsoft.Azure.Management.Compute.Models.Sku(); } this.VirtualMachineScaleSetUpdate.Sku.Tier = this.SkuTier; } if (this.VhdContainer != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers = this.VhdContainer; } if (this.LicenseType != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.LicenseType = this.LicenseType; } if (this.IdentityType != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.Identity == null) { this.VirtualMachineScaleSetUpdate.Identity = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetIdentity(); } this.VirtualMachineScaleSetUpdate.Identity.Type = this.IdentityType; } if (this.SkuName != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.Sku == null) { this.VirtualMachineScaleSetUpdate.Sku = new Microsoft.Azure.Management.Compute.Models.Sku(); } this.VirtualMachineScaleSetUpdate.Sku.Name = this.SkuName; } if (this.PlanPromotionCode != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.Plan == null) { this.VirtualMachineScaleSetUpdate.Plan = new Microsoft.Azure.Management.Compute.Models.Plan(); } this.VirtualMachineScaleSetUpdate.Plan.PromotionCode = this.PlanPromotionCode; } if (this.MaxUnhealthyInstancePercent != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy(); } this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyInstancePercent = this.MaxUnhealthyInstancePercent; } if (this.SkuCapacity != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.Sku == null) { this.VirtualMachineScaleSetUpdate.Sku = new Microsoft.Azure.Management.Compute.Models.Sku(); } this.VirtualMachineScaleSetUpdate.Sku.Capacity = this.SkuCapacity; } if (this.ImageReferenceOffer != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Offer = this.ImageReferenceOffer; } if (this.PauseTimeBetweenBatches != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy == null) { this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy(); } this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy.PauseTimeBetweenBatches = this.PauseTimeBetweenBatches; } if (this.OsDiskCaching != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.Caching = this.OsDiskCaching; } if (this.ImageReferenceVersion != null) { if (this.VirtualMachineScaleSetUpdate == null) { this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile(); } if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Version = this.ImageReferenceVersion; } if (this.VirtualMachineScaleSetUpdate != null && this.VirtualMachineScaleSetUpdate.VirtualMachineProfile != null && this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile != null && this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration != null && this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.LinuxConfiguration != null) { throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified); } } private void BuildPutObject() { if (this.ImageReferenceSku != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Sku = this.ImageReferenceSku; } if (this.EnableAutomaticUpdate != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = this.EnableAutomaticUpdate; } if (this.ManagedDiskStorageAccountType != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetManagedDiskParameters(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.StorageAccountType = this.ManagedDiskStorageAccountType; } if (this.PlanPublisher != null) { if (this.VirtualMachineScaleSet.Plan == null) { this.VirtualMachineScaleSet.Plan = new Microsoft.Azure.Management.Compute.Models.Plan(); } this.VirtualMachineScaleSet.Plan.Publisher = this.PlanPublisher; } if (this.ProvisionVMAgent != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.ProvisionVMAgent = this.ProvisionVMAgent; } if (this.BootDiagnosticsEnabled != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new Microsoft.Azure.Management.Compute.Models.BootDiagnostics(); } this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.Enabled = this.BootDiagnosticsEnabled; } if (this.Overprovision != null) { this.VirtualMachineScaleSet.Overprovision = this.Overprovision; } if (this.MaxBatchInstancePercent != null) { if (this.VirtualMachineScaleSet.UpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy(); } this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy.MaxBatchInstancePercent = this.MaxBatchInstancePercent; } if (this.TimeZone != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.TimeZone = this.TimeZone; } if (this.BootDiagnosticsStorageUri != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new Microsoft.Azure.Management.Compute.Models.BootDiagnostics(); } this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.StorageUri = this.BootDiagnosticsStorageUri; } if (this.AutomaticOSUpgrade != null) { if (this.VirtualMachineScaleSet.UpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } this.VirtualMachineScaleSet.UpgradePolicy.AutomaticOSUpgrade = this.AutomaticOSUpgrade; } if (this.SinglePlacementGroup != null) { this.VirtualMachineScaleSet.SinglePlacementGroup = this.SinglePlacementGroup; } if (this.CustomData != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.CustomData = this.CustomData; } if (this.UpgradePolicyMode != null) { if (this.VirtualMachineScaleSet.UpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } this.VirtualMachineScaleSet.UpgradePolicy.Mode = this.UpgradePolicyMode; } if (this.ImageReferenceId != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Id = this.ImageReferenceId; } if (this.DisablePasswordAuthentication != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new Microsoft.Azure.Management.Compute.Models.LinuxConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.DisablePasswordAuthentication = this.DisablePasswordAuthentication; } if (this.Tag != null) { this.VirtualMachineScaleSet.Tags = this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value); } if (this.PlanName != null) { if (this.VirtualMachineScaleSet.Plan == null) { this.VirtualMachineScaleSet.Plan = new Microsoft.Azure.Management.Compute.Models.Plan(); } this.VirtualMachineScaleSet.Plan.Name = this.PlanName; } if (this.MaxUnhealthyUpgradedInstancePercent != null) { if (this.VirtualMachineScaleSet.UpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy(); } this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyUpgradedInstancePercent = this.MaxUnhealthyUpgradedInstancePercent; } if (this.ImageReferencePublisher != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Publisher = this.ImageReferencePublisher; } if (this.PlanProduct != null) { if (this.VirtualMachineScaleSet.Plan == null) { this.VirtualMachineScaleSet.Plan = new Microsoft.Azure.Management.Compute.Models.Plan(); } this.VirtualMachineScaleSet.Plan.Product = this.PlanProduct; } if (this.ImageUri != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image = new Microsoft.Azure.Management.Compute.Models.VirtualHardDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri = this.ImageUri; } if (this.SkuTier != null) { if (this.VirtualMachineScaleSet.Sku == null) { this.VirtualMachineScaleSet.Sku = new Microsoft.Azure.Management.Compute.Models.Sku(); } this.VirtualMachineScaleSet.Sku.Tier = this.SkuTier; } if (this.VhdContainer != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers = this.VhdContainer; } if (this.LicenseType != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.LicenseType = this.LicenseType; } if (this.IdentityType != null) { if (this.VirtualMachineScaleSet.Identity == null) { this.VirtualMachineScaleSet.Identity = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetIdentity(); } this.VirtualMachineScaleSet.Identity.Type = this.IdentityType; } if (this.SkuName != null) { if (this.VirtualMachineScaleSet.Sku == null) { this.VirtualMachineScaleSet.Sku = new Microsoft.Azure.Management.Compute.Models.Sku(); } this.VirtualMachineScaleSet.Sku.Name = this.SkuName; } if (this.PlanPromotionCode != null) { if (this.VirtualMachineScaleSet.Plan == null) { this.VirtualMachineScaleSet.Plan = new Microsoft.Azure.Management.Compute.Models.Plan(); } this.VirtualMachineScaleSet.Plan.PromotionCode = this.PlanPromotionCode; } if (this.MaxUnhealthyInstancePercent != null) { if (this.VirtualMachineScaleSet.UpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy(); } this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyInstancePercent = this.MaxUnhealthyInstancePercent; } if (this.SkuCapacity != null) { if (this.VirtualMachineScaleSet.Sku == null) { this.VirtualMachineScaleSet.Sku = new Microsoft.Azure.Management.Compute.Models.Sku(); } this.VirtualMachineScaleSet.Sku.Capacity = this.SkuCapacity; } if (this.ImageReferenceOffer != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Offer = this.ImageReferenceOffer; } if (this.PauseTimeBetweenBatches != null) { if (this.VirtualMachineScaleSet.UpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy == null) { this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy(); } this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy.PauseTimeBetweenBatches = this.PauseTimeBetweenBatches; } if (this.OsDiskCaching != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Caching = this.OsDiskCaching; } if (this.ImageReferenceVersion != null) { if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile(); } if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference(); } this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Version = this.ImageReferenceVersion; } if (this.VirtualMachineScaleSet != null && this.VirtualMachineScaleSet.VirtualMachineProfile != null && this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile != null && this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration != null && this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration != null) { throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Numerics.Tests { public static class Support { private static Random s_random; static Support() { s_random = new Random(-55); } public static Random Random { get { return s_random; } } // Valid values in double type public static Double[] doubleValidValues = new Double[] { double.MinValue, -1, 0, double.Epsilon, 1, double.MaxValue, }; // Invalid values in double type public static Double[] doubleInvalidValues = new Double[] { double.NegativeInfinity, double.PositiveInfinity, double.NaN }; // Typical phase values in double type public static Double[] phaseTypicalValues = new Double[] { -Math.PI/2, 0, Math.PI/2 }; public static String[] supportedStdNumericFormats = new String[] { "C", "E", "F", "G", "N", "P", "R" }; private static double GetRandomValue(double mult, bool fIsNegative) { double randomDouble = (mult * s_random.NextDouble()); randomDouble %= (Double)(mult); return fIsNegative ? -randomDouble : randomDouble; } public static double GetRandomDoubleValue(bool fIsNegative) { return GetRandomValue(double.MaxValue, fIsNegative); } public static double GetSmallRandomDoubleValue(bool fIsNegative) { return GetRandomValue(1.0, fIsNegative); } public static Int16 GetRandomInt16Value(bool fIsNegative) { if (fIsNegative) { return ((Int16)s_random.Next(Int16.MinValue, 0)); } else { return ((Int16)s_random.Next(1, Int16.MaxValue)); } } public static Int32 GetRandomInt32Value(bool fIsNegative) { return ((Int32)GetRandomValue(Int32.MaxValue, fIsNegative)); } public static Int64 GetRandomInt64Value(bool fIsNegative) { return ((Int64)GetRandomValue(Int64.MaxValue, fIsNegative)); } public static Byte GetRandomByteValue() { return ((Byte)s_random.Next(1, Byte.MaxValue)); } #if CLS_Compliant public static SByte GetRandomSByteValue(bool fIsNegative) { if (fIsNegative) { return ((SByte) random.Next(SByte.MinValue, 0)); } else { return ((SByte) random.Next(1, SByte.MaxValue)); } } public static UInt16 GetRandomUInt16Value() { return ((UInt16)random.Next(1, UInt16.MaxValue)); } public static UInt32 GetRandomUInt32Value() { return ((UInt32)GetRandomValue(UInt32.MaxValue, false)); } public static UInt64 GetRandomUInt64Value() { return ((UInt64)GetRandomValue(UInt64.MaxValue, false)); } #endif public static Single GetRandomSingleValue(bool fIsNegative) { return ((Single)GetRandomValue(Single.MaxValue, fIsNegative)); } public static BigInteger GetRandomBigIntegerValue(bool fIsNegative) { return ((BigInteger)GetRandomValue(double.MaxValue, fIsNegative)); } public static Decimal GetRandomDecimalValue(bool fIsNegative) { if (fIsNegative) { return ((Decimal)new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), true, (byte)s_random.Next(0, 29))); } else { return ((Decimal)new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), false, (byte)s_random.Next(0, 29))); } } public static double GetRandomPhaseValue(bool fIsNegative) { return GetRandomValue((Math.PI / 2), fIsNegative); } public static bool IsDiffTolerable(double d1, double d2) { if (double.IsInfinity(d1)) { return AreSameInfinity(d1, d2 * 10); } else if (double.IsInfinity(d2)) { return AreSameInfinity(d1 * 10, d2); } else { double diffRatio = (d1 - d2) / d1; diffRatio *= Math.Pow(10, 6); diffRatio = Math.Abs(diffRatio); return (diffRatio < 1); } } private static bool AreSameInfinity(double d1, double d2) { return double.IsNegativeInfinity(d1) == double.IsNegativeInfinity(d2) && double.IsPositiveInfinity(d1) == double.IsPositiveInfinity(d2); } public static void VerifyRealImaginaryProperties(Complex complex, double real, double imaginary, string message) { Assert.True(real.Equals((Double)complex.Real) || IsDiffTolerable(complex.Real, real), message); Assert.True(imaginary.Equals((Double)complex.Imaginary) || IsDiffTolerable(complex.Imaginary, imaginary), message); } public static void VerifyMagnitudePhaseProperties(Complex complex, double magnitude, double phase, string message) { // The magnitude (m) of a complex number (z = x + yi) is the absolute value - |z| = sqrt(x^2 + y^2) // Verification is done using the square of the magnitude since m^2 = x^2 + y^2 double expectedMagnitudeSqr = magnitude * magnitude; double actualMagnitudeSqr = complex.Magnitude * complex.Magnitude; Assert.True(expectedMagnitudeSqr.Equals((Double)(actualMagnitudeSqr)) || IsDiffTolerable(actualMagnitudeSqr, expectedMagnitudeSqr), message); if (double.IsNaN(magnitude)) { phase = double.NaN; } else if (magnitude == 0) { phase = 0; } else if (magnitude < 0) { phase += (phase < 0) ? Math.PI : -Math.PI; } Assert.True(phase.Equals((Double)complex.Phase) || IsDiffTolerable(complex.Phase, phase), message); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.IO.Pipelines.Networking.Windows.RIO.Internal.Winsock; using System.Runtime.InteropServices; using System.Threading; namespace System.IO.Pipelines.Networking.Windows.RIO.Internal { internal unsafe class RioThread { const int maxResults = 1024; const string Kernel_32 = "Kernel32"; const long INVALID_HANDLE_VALUE = -1; private readonly RegisteredIO _rio; private readonly int _id; private readonly IntPtr _completionPort; private readonly IntPtr _completionQueue; private readonly Thread _completionThread; private readonly object _notify; private readonly Thread _notifyThread; private readonly CancellationToken _token; private readonly Queue<NotifyBatch> _notifyBatches; private readonly Queue<NotifyBatch> _processedBatches; private PipeFactory _factory; private Dictionary<long, RioTcpConnection> _connections; private List<BufferMapping> _bufferIdMappings; public IntPtr ReceiveCompletionQueue => _completionQueue; public IntPtr SendCompletionQueue => _completionQueue; public IntPtr CompletionPort => _completionPort; public PipeFactory PipeFactory => _factory; public RioThread(int id, CancellationToken token, IntPtr completionPort, IntPtr completionQueue, RegisteredIO rio) { _id = id; _rio = rio; _token = token; if (CpuInfo.LogicalProcessorCount > CpuInfo.PhysicalCoreCount) { _completionThread = new Thread(RunLogicalCompletions) { Name = $"RIO Completion Thread {id:00}", IsBackground = true }; _notifyBatches = new Queue<NotifyBatch>(16); _notify = new object(); _notifyThread = new Thread(RunNotifies) { Name = $"RIO Notify Thread {id:00}", IsBackground = true }; _processedBatches = new Queue<NotifyBatch>(16); } else { _completionThread = new Thread(RunPhysicalCompletions) { Name = $"RIO Completion Thread {id:00}", IsBackground = true }; } _completionPort = completionPort; _completionQueue = completionQueue; } public void AddConnection(long key, RioTcpConnection value) { lock (_connections) { _connections.Add(key, value); } } public void RemoveConnection(long key) { lock (_connections) { _connections.Remove(key); } } private IntPtr GetBufferId(IntPtr address, out long startAddress) { var id = IntPtr.Zero; startAddress = 0; lock (_bufferIdMappings) { var addressLong = address.ToInt64(); // Can binary search if it's too slow foreach (var mapping in _bufferIdMappings) { if (addressLong >= mapping.Start && addressLong <= mapping.End) { id = mapping.Id; startAddress = mapping.Start; break; } } } return id; } public unsafe RioBufferSegment GetSegmentFromMemory(Buffer<byte> memory) { // It's ok to unpin the handle here because the memory is from the pool // we created, which is already pinned. var pin = memory.Retain(pin: true); var spanPtr = (IntPtr)pin.PinnedPointer; pin.Dispose(); long startAddress; long spanAddress = spanPtr.ToInt64(); var bufferId = GetBufferId(spanPtr, out startAddress); checked { var offset = (uint)(spanAddress - startAddress); return new RioBufferSegment(bufferId, offset, (uint)memory.Length); } } private void OnSlabAllocated(MemoryPoolSlab slab) { lock (_bufferIdMappings) { var memoryPtr = slab.NativePointer; var bufferId = _rio.RioRegisterBuffer(memoryPtr, (uint)slab.Length); var addressLong = memoryPtr.ToInt64(); _bufferIdMappings.Add(new BufferMapping { Id = bufferId, Start = addressLong, End = addressLong + slab.Length }); } } private void OnSlabDeallocated(MemoryPoolSlab slab) { var memoryPtr = slab.NativePointer; var addressLong = memoryPtr.ToInt64(); lock (_bufferIdMappings) { for (int i = _bufferIdMappings.Count - 1; i >= 0; i--) { if (addressLong == _bufferIdMappings[i].Start) { _bufferIdMappings.RemoveAt(i); break; } } } } public void Start() { _completionThread.Start(this); _notifyThread?.Start(this); } private static void RunLogicalCompletions(object state) { var thread = ((RioThread)state); #if NET451 Thread.BeginThreadAffinity(); #endif var nativeThread = GetCurrentThread(); var affinity = GetAffinity(thread._id); nativeThread.ProcessorAffinity = new IntPtr((long)affinity); thread._connections = new Dictionary<long, RioTcpConnection>(); thread._bufferIdMappings = new List<BufferMapping>(); var memoryPool = new MemoryPool(); memoryPool.RegisterSlabAllocationCallback((slab) => thread.OnSlabAllocated(slab)); memoryPool.RegisterSlabDeallocationCallback((slab) => thread.OnSlabDeallocated(slab)); thread._factory = new PipeFactory(memoryPool); thread.ProcessLogicalCompletions(); #if NET451 Thread.EndThreadAffinity(); #endif } private static void RunPhysicalCompletions(object state) { var thread = ((RioThread)state); #if NET451 Thread.BeginThreadAffinity(); #endif var nativeThread = GetCurrentThread(); var affinity = GetAffinity(thread._id); nativeThread.ProcessorAffinity = new IntPtr((long)affinity); thread._connections = new Dictionary<long, RioTcpConnection>(); thread._bufferIdMappings = new List<BufferMapping>(); var memoryPool = new MemoryPool(); memoryPool.RegisterSlabAllocationCallback((slab) => thread.OnSlabAllocated(slab)); memoryPool.RegisterSlabDeallocationCallback((slab) => thread.OnSlabDeallocated(slab)); thread._factory = new PipeFactory(memoryPool); thread.ProcessPhysicalCompletions(); #if NET451 Thread.EndThreadAffinity(); #endif } private static void RunNotifies(object state) { var thread = ((RioThread)state); #if NET451 Thread.BeginThreadAffinity(); #endif var nativeThread = GetCurrentThread(); var affinity = GetPairedAffinity(thread._id); nativeThread.ProcessorAffinity = new IntPtr((long)affinity); thread.ProcessNotifies(); #if NET451 Thread.EndThreadAffinity(); #endif } private struct NotifyBatch { public RioTcpConnection[] ConnectionsToSignal; public uint Count; } private void ProcessNotifies() { while (!_token.IsCancellationRequested) { NotifyBatch batch; lock (_notify) { if (_notifyBatches.Count == 0) { Monitor.Wait(_notify); } batch = _notifyBatches.Dequeue(); } var count = batch.Count; var connectionsToSignal = batch.ConnectionsToSignal; Notify(connectionsToSignal, count); lock (_processedBatches) { _processedBatches.Enqueue(batch); } } } private static void Notify(RioTcpConnection[] connectionsToSignal, uint count) { for (var i = 0; i < connectionsToSignal.Length; i++) { if (i >= count) { break; } var connection = connectionsToSignal[i]; if (connection != null) { connection.ReceiveEndComplete(); connectionsToSignal[i] = null; } } } private void ProcessLogicalCompletions() { RioRequestResult* results = stackalloc RioRequestResult[maxResults]; _rio.Notify(ReceiveCompletionQueue); while (!_token.IsCancellationRequested) { NativeOverlapped* overlapped; uint bytes, key; var success = GetQueuedCompletionStatus(CompletionPort, out bytes, out key, out overlapped, -1); if (success) { var activatedNotify = false; while (true) { var count = _rio.DequeueCompletion(ReceiveCompletionQueue, (IntPtr)results, maxResults); if (count == 0) { if (!activatedNotify) { activatedNotify = true; _rio.Notify(ReceiveCompletionQueue); continue; } break; } var gotBatch = false; var batch = default(NotifyBatch); lock (_processedBatches) { if (_processedBatches.Count > 0) { batch = _processedBatches.Dequeue(); batch.Count = count; gotBatch = true; } } if (!gotBatch) { batch = new NotifyBatch() { ConnectionsToSignal = new RioTcpConnection[maxResults], Count = count }; } var connectionsToSignal = batch.ConnectionsToSignal; Complete(results, count, connectionsToSignal); lock (_notify) { _notifyBatches.Enqueue(batch); Monitor.Pulse(_notify); } if (!activatedNotify) { activatedNotify = true; _rio.Notify(ReceiveCompletionQueue); } } } else { var error = GetLastError(); if (error != 258) { throw new Exception($"ERROR: GetQueuedCompletionStatusEx returned {error}"); } } } } private unsafe void Complete(RioRequestResult* results, uint count, RioTcpConnection[] connectionsToSignal) { for (var i = 0; i < count; i++) { var result = results[i]; RioTcpConnection connection; bool found; lock (_connections) { found = _connections.TryGetValue(result.ConnectionCorrelation, out connection); } if (found) { if (result.RequestCorrelation >= 0) { connection.ReceiveBeginComplete(result.BytesTransferred); connectionsToSignal[i] = connection; } else { connection.SendComplete(result.RequestCorrelation); connectionsToSignal[i] = null; } } else { connectionsToSignal[i] = null; } } } private void ProcessPhysicalCompletions() { RioRequestResult* results = stackalloc RioRequestResult[maxResults]; var connectionsToSignal = new RioTcpConnection[maxResults]; _rio.Notify(ReceiveCompletionQueue); while (!_token.IsCancellationRequested) { NativeOverlapped* overlapped; uint bytes, key; var success = GetQueuedCompletionStatus(CompletionPort, out bytes, out key, out overlapped, -1); if (success) { var activatedNotify = false; while (true) { var count = _rio.DequeueCompletion(ReceiveCompletionQueue, (IntPtr)results, maxResults); if (count == 0) { if (!activatedNotify) { activatedNotify = true; _rio.Notify(ReceiveCompletionQueue); continue; } break; } Complete(results, count, connectionsToSignal); Notify(connectionsToSignal, count); if (!activatedNotify) { activatedNotify = true; _rio.Notify(ReceiveCompletionQueue); } } } else { var error = GetLastError(); if (error != 258) { throw new Exception($"ERROR: GetQueuedCompletionStatusEx returned {error}"); } } } } [DllImport(Kernel_32, SetLastError = true)] private static extern bool GetQueuedCompletionStatus(IntPtr CompletionPort, out uint lpNumberOfBytes, out uint lpCompletionKey, out NativeOverlapped* lpOverlapped, int dwMilliseconds); [DllImport(Kernel_32, SetLastError = true)] private static extern long GetLastError(); [DllImport("kernel32.dll")] private static extern int GetCurrentThreadId(); private static ProcessThread GetCurrentThread() { var id = GetCurrentThreadId(); var processThreads = Process.GetCurrentProcess().Threads; for (var i = 0; i < processThreads.Count; i++) { var thread = processThreads[i]; if (thread.Id == id) { return thread; } } return null; } private static ulong GetAffinity(int threadId) { const int lshift = sizeof(ulong) * 8 - 1; var bitMask = CpuInfo.PhysicalCoreMask; var coreId = 0; for (var i = 0; i <= lshift; i++) { var bitTest = 1UL << i; if ((bitMask & bitTest) == bitTest) { if (coreId == threadId) { return bitTest; } coreId++; } } unchecked { return (ulong)-1; } } private static ulong GetPairedAffinity(int threadId) { const int lshift = sizeof(ulong) * 8 - 1; var bitMask = CpuInfo.SecondaryCoreMask; var coreId = 0; for (var i = 0; i <= lshift; i++) { var bitTest = 1UL << i; if ((bitMask & bitTest) == bitTest) { if (coreId == threadId) { return bitTest; } coreId++; } } unchecked { return (ulong)-1; } } private struct BufferMapping { public IntPtr Id; public long Start; public long End; public override string ToString() { return $"{Id} ({Start}) - ({End})"; } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows.Forms; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Localization; using OpenLiveWriter.CoreServices.Layout; namespace OpenLiveWriter.FileDestinations { public delegate void ErrorHandler(Exception e); public class PublishFolderPicker : ApplicationDialog { private TreeView destinationTree; private IContainer components = null; private Button buttonOK; private Button buttonCancel; private ImageList imageList; private Label label1; private NewFolderButton buttonNewFolder; private TreeNode RootNode; private ErrorHandler errorHandler; public PublishFolderPicker(string destinationName, ErrorHandler errorCallback) : this(destinationName, errorCallback, "/") { } public PublishFolderPicker(string destinationName, ErrorHandler errorCallback, string rootPath) { // This call is required by the Windows Form Designer. InitializeComponent(); destinationTree.RightToLeftLayout = true; this.buttonOK.Text = Res.Get(StringId.OKButtonText); this.buttonCancel.Text = Res.Get(StringId.CancelButton); this.label1.Text = Res.Get(StringId.PublishFolderPickerCaption); this.buttonNewFolder.ButtonText = Res.Get(StringId.NewFolder); this.buttonNewFolder.AccessibleName = Res.Get(StringId.NewFolder); this.buttonNewFolder.ToolTip = Res.Get(StringId.NewFolderTooltip); this.Text = Res.Get(StringId.PublishFolderPickerTitle); //set the error handler. errorHandler = errorCallback; //Root Node RootNode = new TreeNode(); // configure tree RootNode.Text = destinationName; RootNode.Tag = rootPath; destinationTree.Nodes.Add(RootNode); destinationTree.SelectedNode = RootNode; destinationTree.SelectedNode.ImageIndex = 0; } public static string BrowseFTPDestination(string name, WinInetFTPFileDestination destination, string currentPath, ErrorHandler errorHandler, IWin32Window owner) { PublishFolderPicker folderPicker = new PublishFolderPicker(name, errorHandler); using (folderPicker) { try { using (new WaitCursor()) destination.Connect(); folderPicker.Destination = destination; //default the selected path to what's in the textField (if it exists!) if (!currentPath.Equals("")) { if (!currentPath.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { currentPath = destination.HomeDir + "/" + currentPath; } folderPicker.SelectedPath = currentPath; } else { string currDirectory = destination.HomeDir; if (!currDirectory.StartsWith("/", StringComparison.OrdinalIgnoreCase)) currDirectory = "/" + currDirectory; folderPicker.SelectedPath = currDirectory; } if (folderPicker.ShowDialog(owner) == DialogResult.OK) { return folderPicker.SelectedPath; } } catch (Exception ex) { if (errorHandler != null) errorHandler(ex); } finally { try { destination.Disconnect(); } catch (Exception) { //eat it since we've already reported the error and this error //is probably because no valid connection was ever established } } return null; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PublishFolderPicker)); this.destinationTree = new System.Windows.Forms.TreeView(); this.imageList = new System.Windows.Forms.ImageList(this.components); this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.buttonNewFolder = new OpenLiveWriter.Controls.NewFolderButton(this.components); this.SuspendLayout(); // // destinationTree // this.destinationTree.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.destinationTree.HideSelection = false; this.destinationTree.HotTracking = true; this.destinationTree.ImageIndex = 0; this.destinationTree.ImageList = this.imageList; this.destinationTree.Location = new System.Drawing.Point(11, 33); this.destinationTree.Name = "destinationTree"; this.destinationTree.SelectedImageIndex = 0; this.destinationTree.Size = new System.Drawing.Size(312, 265); this.destinationTree.TabIndex = 0; this.destinationTree.MouseDown += new System.Windows.Forms.MouseEventHandler(this.destinationTree_MouseDown); // // imageList // this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; this.imageList.Images.SetKeyName(0, ""); this.imageList.Images.SetKeyName(1, ""); this.imageList.Images.SetKeyName(2, ""); this.imageList.Images.SetKeyName(3, ""); this.imageList.Images.SetKeyName(4, ""); // // buttonOK // this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonOK.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonOK.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.buttonOK.Location = new System.Drawing.Point(133, 306); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(90, 27); this.buttonOK.TabIndex = 1; this.buttonOK.Text = "OK"; this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonCancel.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.buttonCancel.Location = new System.Drawing.Point(232, 306); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(90, 27); this.buttonCancel.TabIndex = 2; this.buttonCancel.Text = "Cancel"; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // label1 // this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label1.Location = new System.Drawing.Point(11, 11); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(247, 19); this.label1.TabIndex = 5; this.label1.Text = "Select a folder to publish to:"; // // buttonNewFolder // this.buttonNewFolder.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.buttonNewFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonNewFolder.AutoSizeHeight = true; this.buttonNewFolder.AutoSizeWidth = true; this.buttonNewFolder.BitmapDisabled = ((System.Drawing.Bitmap)(resources.GetObject("buttonNewFolder.BitmapDisabled"))); this.buttonNewFolder.BitmapEnabled = ((System.Drawing.Bitmap)(resources.GetObject("buttonNewFolder.BitmapEnabled"))); this.buttonNewFolder.BitmapSelected = ((System.Drawing.Bitmap)(resources.GetObject("buttonNewFolder.BitmapSelected"))); this.buttonNewFolder.ButtonText = "New Folder"; this.buttonNewFolder.Location = new System.Drawing.Point(208, 5); this.buttonNewFolder.Name = "buttonNewFolder"; this.buttonNewFolder.Size = new System.Drawing.Size(117, 26); this.buttonNewFolder.TabIndex = 3; this.buttonNewFolder.ToolTip = "Create a new folder"; this.buttonNewFolder.Click += new System.EventHandler(this.buttonNewFolder_Click); // // PublishFolderPicker // this.AcceptButton = this.buttonOK; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(336, 341); this.Controls.Add(this.buttonNewFolder); this.Controls.Add(this.label1); this.Controls.Add(this.buttonOK); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.destinationTree); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "PublishFolderPicker"; this.Text = "Browse For Folder"; this.ResumeLayout(false); } #endregion public string SelectedPath { get { return this.destinationTree.SelectedNode.Tag.ToString(); } set { string rootPath = RootNode.Tag.ToString(); if (value.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase)) { string relativePath = value.Substring(rootPath.Length); SelectedRelativePath = relativePath; } else { Debug.Fail(String.Format(CultureInfo.InvariantCulture, "specified path [{0}] is not within destination root [{1}]", value, rootPath)); } } } public string SelectedRelativePath { get { // calculate root path length string rootPath = RootNode.Tag.ToString(); int rootPathLength = rootPath.Length; if (!(rootPath.EndsWith("\\", StringComparison.OrdinalIgnoreCase) || rootPath.EndsWith("/", StringComparison.OrdinalIgnoreCase))) rootPathLength++; string fullPath = destinationTree.SelectedNode.Tag.ToString(); if (rootPathLength < fullPath.Length) return fullPath.Substring(rootPathLength); else return String.Empty; } set { using (new WaitCursor()) { //walk from the root node and select the specified path string path = value; string[] paths = path.Split(new char[] { destination.PathDelimiterChar }); TreeNode currNode = RootNode; //Build the tree for the selected path //note: skip the first part since it should be the root for (int i = 0; i < paths.Length; i++) { string pathPart = paths[i]; if (pathPart == string.Empty) { //this case can occur if the path is "/" continue; } TreeNode nextNode = null; EnumDirectories(currNode); TreeNodeCollection nodes = currNode.Nodes; //search for a node in the tree the matches the pathPath exactly //note: exact match is required for UNIX-based FTP destinations foreach (TreeNode node in nodes) { if (node.Text.Equals(pathPart)) { nextNode = node; break; } } //if the exact path part wasn't found, try a case-insensitive comparison if (nextNode == null) { foreach (TreeNode node in nodes) { if (node.Text.ToLower(CultureInfo.CurrentCulture).Equals(pathPart.ToLower(CultureInfo.CurrentCulture))) { nextNode = node; break; } } } //If the elements in the folder can't be listed, then just shove it into the tree. //Note: This case is necessary for shared FTP enviroments where the user starts //out in a writable homedir but the parent dirs aren't browsable. if (nextNode == null) { string fullPath = destination.CombinePath(currNode.Tag.ToString(), pathPart); if (destination.DirectoryExists(fullPath)) { nextNode = createFolderNode(currNode, pathPart); } else { //we hit the end of the valid part of this path break; } } currNode = nextNode; } destinationTree.SelectedNode = currNode; } } } private FileDestination destination; /// <summary> /// Set the destination that this dialog will choose a folder from. /// </summary> public FileDestination Destination { get { return destination; } set { destination = value; destinationTree.AfterSelect += new TreeViewEventHandler(destinationTree_AfterSelect); } } private void destinationTree_AfterSelect(object sender, TreeViewEventArgs e) { EnumDirectories(e.Node); e.Node.EnsureVisible(); } //Enumerates the destination directory associated with this treenode and populates //the TreeNode with nodes representing folders in the directory. private void EnumDirectories(TreeNode ParentNode) { destinationTree.SelectedNode = ParentNode; string DirectoryPath = ParentNode.Tag.ToString(); if (ParentNode.Nodes.Count == 0) { if (!DirectoryPath.EndsWith(destination.PathDelimiter, StringComparison.OrdinalIgnoreCase)) DirectoryPath += destination.PathDelimiter; try { using (new WaitCursor()) { string[] directories = Destination.ListDirectories(DirectoryPath); if (directories.Length == 0) { string homeDir = ((WinInetFTPFileDestination)Destination).HomeDir; // break homedir and directorypath into path elements if (IsParentPath(DirectoryPath, homeDir)) { string restOfPath = homeDir.Substring(DirectoryPath.Length); if (restOfPath.Length > 0) { int nextChunkLen = restOfPath.IndexOf(destination.PathDelimiter, StringComparison.OrdinalIgnoreCase); if (nextChunkLen == -1) nextChunkLen = restOfPath.Length; string nextChunk = restOfPath.Substring(0, nextChunkLen); TreeNode newNode = createFolderNode(ParentNode, nextChunk); newNode.EnsureVisible(); } } } else { foreach (string directory in directories) { if (directory != "." && directory != "..") { TreeNode newNode = createFolderNode(ParentNode, directory); newNode.EnsureVisible(); } } } } } catch (Exception e) { Trace.WriteLine("Unexpected exception enumerating Publish Folder directories: " + e.ToString()); } } } private bool IsParentPath(string parent, string child) { if (parent.Length == 0) return false; if (!child.StartsWith(parent, StringComparison.OrdinalIgnoreCase)) return false; string[] parentElements = StringHelper.Split(parent, Destination.PathDelimiter); string[] childElements = StringHelper.Split(child, Destination.PathDelimiter); for (int i = 0; i < parentElements.Length; i++) { if (childElements[i] != parentElements[i]) return false; } return true; } private void buttonOK_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; } private void buttonCancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } private void buttonNewFolder_Click(object sender, EventArgs e) { using (new WaitCursor()) { TreeNode selectedNode = destinationTree.SelectedNode; string selectedPath = selectedNode.Tag.ToString(); NewFolder newFolder = new NewFolder(); using (newFolder) { if (newFolder.ShowDialog(this.FindForm()) == DialogResult.OK) { try { string newFolderName = newFolder.NewFolderName; string newPath = Destination.CombinePath(selectedPath, newFolderName); using (new WaitCursor()) { Destination.CreateDirectory(newPath); refreshNode(selectedNode); } SelectedPath = newPath; destinationTree.Focus(); } catch (Exception ex) { if (errorHandler != null) errorHandler(ex); else throw ex; } } } } } //causes the specified parent node to refresh its listing of children private void refreshNode(TreeNode parent) { //dump the children nodes, and re-enumerate the directory. parent.Nodes.Clear(); EnumDirectories(parent); } private TreeNode createFolderNode(TreeNode parent, string dirName) { TreeNode TempNode = new TreeNode(); TempNode.Text = dirName; TempNode.Tag = destination.CombinePath(parent.Tag.ToString(), dirName); TempNode.ImageIndex = 3; TempNode.SelectedImageIndex = 2; parent.Nodes.Add(TempNode); return TempNode; } private void destinationTree_MouseDown(object sender, MouseEventArgs e) { // make right-click work for selection (defect 2518) if (e.Button == MouseButtons.Right) { TreeNode node = destinationTree.GetNodeAt(e.X, e.Y); if (node != null) destinationTree.SelectedNode = node; } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); using (new AutoGrow(this, AnchorStyles.Bottom, false)) { LayoutHelper.NaturalizeHeightAndDistribute(3, label1, destinationTree, new ControlGroup(buttonOK, buttonCancel)); buttonNewFolder.Left = destinationTree.Right - buttonNewFolder.Width; if (label1.Right > buttonNewFolder.Left) { buttonNewFolder.Text = null; buttonNewFolder.ButtonText = null; buttonNewFolder.Width = buttonNewFolder.BitmapEnabled.Width + 8; buttonNewFolder.Left = destinationTree.Right - buttonNewFolder.Width; } buttonNewFolder.Top = destinationTree.Top - buttonNewFolder.Height - 1; } } } }
namespace Nancy.Tests.Unit.Routing { using System; using Nancy.Routing; using Xunit; public class DefaultRoutePatternMatcherFixture { private readonly DefaultRoutePatternMatcher matcher; public DefaultRoutePatternMatcherFixture() { this.matcher = new DefaultRoutePatternMatcher(); } [Fact] public void Should_not_trim_trailing_slash_if_requesting_root() { // Given, When var results = this.matcher.Match("/", "/", new string[] { }, null); // Then results.IsMatch.ShouldBeTrue(); } [Fact] public void Should_ignore_trailing_slash_on_route_path() { // Given, When var results = this.matcher.Match("/foo/bar", "/foo/bar/", new[] { "foo", "bar" }, null); // Then results.IsMatch.ShouldBeTrue(); } [Fact] public void Should_ignore_trailing_slash_on_request_uri() { // Given, When var results = this.matcher.Match("/foo/bar/", "/foo/bar", new[] { "foo", "bar" }, null); // Then results.IsMatch.ShouldBeTrue(); } [Fact] public void Should_return_match_result_when_paths_matched() { // Given, When var results = this.matcher.Match("/foo/bar", "/foo/bar", new[] { "foo", "bar" }, null); // Then results.IsMatch.ShouldBeTrue(); } [Fact] public void Should_return_match_result_with_context_of_current_request_when_paths_matched() { // Given var context = new NancyContext(); // When var results = this.matcher.Match("/foo/bar", "/foo/bar", new[] { "foo", "bar" }, context); // Then results.Context.ShouldBeSameAs(context); } [Fact] public void Should_return_match_result_with_context_of_current_request_when_paths_do_not_match() { // Given var context = new NancyContext(); // When var results = this.matcher.Match("/foo/bar", "/bar/foo", new[] { "foo", "bar" }, context); // Then results.Context.ShouldBeSameAs(context); } [Fact] public void Should_return_negative_match_result_when_paths_does_not_match() { // Given, When var results = this.matcher.Match("/foo/bar", "/bar/foo", new[] { "bar", "foo" }, null); // Then results.IsMatch.ShouldBeFalse(); } [Fact] public void Should_be_case_insensitive_when_checking_for_match() { // Given, When var results = this.matcher.Match("/FoO/baR", "/fOO/bAr", new[] { "fOO", "bAr" }, null); // Then results.IsMatch.ShouldBeTrue(); } [Fact] public void Should_capture_parameters() { // Given, When var results = this.matcher.Match("/foo/bar/baz", "/foo/{bar}/{baz}", new[] { "foo", "{bar}", "{baz}" }, null); // Then ((string)results.Parameters["bar"]).ShouldEqual("bar"); ((string)results.Parameters["baz"]).ShouldEqual("baz"); } [Fact] public void Should_treat_parameters_as_greedy() { // Given, When var results = this.matcher.Match("/foo/bar/baz", "/foo/{bar}", new[] { "foo", "{bar}" }, null); // Then ((string)results.Parameters["bar"]).ShouldEqual("bar/baz"); } [Fact] public void Should_allow_regex_in_route_definition_and_capture_specified_parameters() { // Given, When var results = this.matcher.Match("/foo/1234", @"/(?<foo>foo)/(?<bar>\d{4})/", new[] { "(?<foo>foo)", @"(?<bar>\d{4})" }, null); // Then results.IsMatch.ShouldBeTrue(); ((string)results.Parameters["foo"]).ShouldEqual("foo"); ((string)results.Parameters["bar"]).ShouldEqual("1234"); } [Fact] public void Should_allow_regex_in_route_definition_and_return_negative_result_when_it_does_not_match() { // Given, When var results = this.matcher.Match("/foo/bar", @"/foo/(?<bar>[0-9]*)", new[] { "foo", @"(?<bar>[0-9]*)" }, null); // Then results.IsMatch.ShouldBeFalse(); } [Fact] public void Should_not_url_decode_captured_parameters() { // Given var parameter = Uri.EscapeUriString("baa ram ewe{}"); // When var results = this.matcher.Match("/foo/" + parameter, "/foo/{bar}", new[] { "foo", @"{bar}" }, null); //Then ((string)results.Parameters["bar"]).ShouldEqual(parameter); } [Fact] public void Should_allow_all_of_the_unreserved_rfc_1738_characters_in_the_capture_segments() { // Given const string parameter = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.!*'()"; // When var results = this.matcher.Match("/foo/" + parameter, "/foo/{bar}", new[] { "foo", @"{bar}" }, null); // Then ((string)results.Parameters["bar"]).ShouldEqual(parameter); } [Fact] public void Should_allow_all_of_the_unreserved_rfc_1738_characters_in_the_non_capture_segments() { // Given const string parameter = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.!*'()"; // When var results = this.matcher.Match("/foo/" + parameter, "/foo/" + parameter, new[] { "foo", parameter }, null); // Then results.IsMatch.ShouldBeTrue(); } [Fact] public void Should_allow_underscore_in_parameter_key() { // Given const string parameter = "lol"; // When var results = this.matcher.Match("/foo/" + parameter, "/foo/{b_ar}", new[] { "foo", "{b_ar}" }, null); // Then ((string)results.Parameters["b_ar"]).ShouldEqual(parameter); } [Fact] public void Should_capture_parameters_when_the_segment_contains_more_characters_after_parameter_declaration() { // Given const string parameter = "filename"; // When var results = this.matcher.Match("/foo/" + parameter + ".cshtml", "/foo/{name}.cshtml", new[] { "foo", "{name}.cshtml" }, null); // Then ((string)results.Parameters["name"]).ShouldEqual(parameter); } [Fact] public void Should_capture_parameters_even_when_it_is_surrounded_by_additional_characters() { // Given const string parameter = "filename"; // When var results = this.matcher.Match("/foo/bar" + parameter + ".cshtml", "/foo/bar{name}.cshtml", new[] { "foo", "bar{name}.cshtml" }, null); // Then ((string)results.Parameters["name"]).ShouldEqual(parameter); } [Fact] public void Should_capture_multiple_parameters() { // Given, When var results = this.matcher.Match("/foo/filename.cshtml", "/foo/{name}.{format}", new[] { "foo", "{name}.{format}" }, null); // Then ((string)results.Parameters["name"]).ShouldEqual("filename"); ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_capture_multiple_parameters_that_are_surrounded_by_characters() { // Given, When var results = this.matcher.Match("/foo/barfilename.cshtmlbaz", "/foo/bar{name}.{format}baz", new[] { "foo", "bar{name}.{format}baz" }, null); // Then ((string)results.Parameters["name"]).ShouldEqual("filename"); ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_support_optional_segments() { // Given, When var results = this.matcher.Match("/foo", "/foo/{bar?}", new[] { "foo", "{bar?}" }, null); // Then results.IsMatch.ShouldBeTrue(); } [Fact] public void Should_support_default_values_for_optional_parameters() { // Given, When var results = this.matcher.Match("/foo", "/foo/{bar?hiya}", new[] { "foo", "{bar?hiya}" }, null); // Then ((string)results.Parameters["bar"]).ShouldEqual("hiya"); } [Fact] public void Should_use_captured_value_for_optional_parameter_when_supplied() { // Given, When var results = this.matcher.Match("/foo/ninjah", "/foo/{bar?hiya}", new[] { "foo", "{bar?hiya}" }, null); // Then ((string)results.Parameters["bar"]).ShouldEqual("ninjah"); } [Fact] public void Should_support_non_optional_parameters_after_optional_parameter() { // Given, When var results = this.matcher.Match("/foo/andreas", "/foo/{bar?hiya}/{name}", new[] { "foo", "{bar?hiya}", "{name}" }, null); // Then ((string)results.Parameters["bar"]).ShouldEqual("hiya"); ((string)results.Parameters["name"]).ShouldEqual("andreas"); } [Fact] public void Should_use_captured_value_for_optional_parameter_when_value_was_supplied_and_route_contains_additional_parameters() { // Given, When var results = this.matcher.Match("/foo/bye/andreas", "/foo/{bar?hiya}/{name}", new[] { "foo", "{bar?hiya}", "{name}" }, null); // Then ((string)results.Parameters["bar"]).ShouldEqual("bye"); ((string)results.Parameters["name"]).ShouldEqual("andreas"); } [Fact] public void Should_support_combination_of_optional_and_required_parameters_in_same_segment() { // Given, When var results = this.matcher.Match("/foo/filename.cshtml", "/foo/{name?}.{format}", new[] { "foo", "{name?}.{format}" }, null); // Then ((string)results.Parameters["name"]).ShouldEqual("filename"); ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_support_multiple_optional_parameters_in_same_segment() { // Given, When var results = this.matcher.Match("/foo/filename.cshtml", "/foo/{name?}.{format?}", new[] { "foo", "{name?}.{format?}" }, null); // Then ((string)results.Parameters["name"]).ShouldEqual("filename"); ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_support_single_default_value_parameter_when_segment_contains_multiple_optional_parameters() { // Given, When var results = this.matcher.Match("/foo/filename.cshtml", "/foo/{name?stuff}.{format?}", new[] { "foo", "{name?stuff}.{format?}" }, null); // Then ((string)results.Parameters["name"]).ShouldEqual("filename"); ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_support_default_values_for_all_parametes_when_segment_contains_multiple_parameters() { // Given, When var results = this.matcher.Match("/foo/filename.cshtml", "/foo/{name?stuff}.{format?}", new[] { "foo", "{name?stuff}.{format?}" }, null); // Then ((string)results.Parameters["name"]).ShouldEqual("filename"); ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_support_literals_after_optional_parameter_when_value_was_supplied() { // Given, When var results = this.matcher.Match("/foo/cshtmlbaz", "/foo/{format?}baz", new[] { "foo", "{format?}baz" }, null); // Then ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_support_literals_after_optional_parameter_when_value_was_not_supplied() { // Given, When var results = this.matcher.Match("/foo/baz", "/foo/{format?cshtml}baz", new[] { "foo", "{format?cshtml}baz" }, null); // Then ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_support_literals_before_optional_parameter_when_value_was_supplied() { // Given, When var results = this.matcher.Match("/foo/barcshtml", "/foo/bar{format}", new[] { "foo", "bar{format?cshtml}" }, null); // Then ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } [Fact] public void Should_support_literals_before_optional_parameter_when_value_was_not_supplied() { // Given, When var results = this.matcher.Match("/foo/bar", "/foo/bar{format?cshtml}", new[] { "foo", "bar{format?cshtml}" }, null); // Then ((string)results.Parameters["format"]).ShouldEqual("cshtml"); } } }
// 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.Runtime.InteropServices; namespace System.Management { //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Represents the set of methods available in the collection.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This sample demonstrates enumerate all methods in a ManagementClass object. /// class Sample_MethodDataCollection /// { /// public static int Main(string[] args) { /// ManagementClass diskClass = new ManagementClass("win32_logicaldisk"); /// MethodDataCollection diskMethods = diskClass.Methods; /// foreach (MethodData method in diskMethods) { /// Console.WriteLine("Method = " + method.Name); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates enumerate all methods in a ManagementClass object. /// Class Sample_MethodDataCollection /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim diskClass As New ManagementClass("win32_logicaldisk") /// Dim diskMethods As MethodDataCollection = diskClass.Methods /// Dim method As MethodData /// For Each method In diskMethods /// Console.WriteLine("Method = " &amp; method.Name) /// Next method /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class MethodDataCollection : ICollection, IEnumerable { private ManagementObject parent; private class enumLock { } //used to lock usage of BeginMethodEnum/NextMethod internal MethodDataCollection(ManagementObject parent) : base() { this.parent = parent; } // //ICollection // /// <summary> /// <para>Represents the number of objects in the <see cref='System.Management.MethodDataCollection'/>.</para> /// </summary> /// <value> /// <para> The number of objects in the <see cref='System.Management.MethodDataCollection'/>. </para> /// </value> public int Count { get { int i = 0; IWbemClassObjectFreeThreaded inParameters = null, outParameters = null; string methodName; int status = (int)ManagementStatus.Failed; #pragma warning disable CA2002 lock(typeof(enumLock)) #pragma warning restore CA2002 { try { status = parent.wbemObject.BeginMethodEnumeration_(0); if (status >= 0) { methodName = ""; // Condition primer to branch into the while loop. while (methodName != null && status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA) { methodName = null; inParameters = null; outParameters = null; status = parent.wbemObject.NextMethod_(0, out methodName, out inParameters, out outParameters); if (status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA) i++; } parent.wbemObject.EndMethodEnumeration_(); // Ignore status. } } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } } // lock if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return i; } } /// <summary> /// <para>Indicates whether the object is synchronized.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the object is synchronized; /// otherwise, <see langword='false'/>.</para> /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// <para>Represents the object to be used for synchronization.</para> /// </summary> /// <value> /// <para>The object to be used for synchronization.</para> /// </value> public object SyncRoot { get { return this; } } /// <overload> /// <para>Copies the <see cref='System.Management.MethodDataCollection'/> into an array.</para> /// </overload> /// <summary> /// <para> Copies the <see cref='System.Management.MethodDataCollection'/> into an array.</para> /// </summary> /// <param name='array'>The array to which to copy the collection. </param> /// <param name='index'>The index from which to start. </param> public void CopyTo(Array array, int index) { //Use an enumerator to get the MethodData objects and attach them into the target array foreach (MethodData m in this) array.SetValue(m, index++); } /// <summary> /// <para>Copies the <see cref='System.Management.MethodDataCollection'/> to a specialized <see cref='System.Management.MethodData'/> /// array.</para> /// </summary> /// <param name='methodArray'>The destination array to which to copy the <see cref='System.Management.MethodData'/> objects.</param> /// <param name=' index'>The index in the destination array from which to start the copy.</param> public void CopyTo(MethodData[] methodArray, int index) { CopyTo((Array)methodArray, index); } // // IEnumerable // IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)(new MethodDataEnumerator(parent)); } /// <summary> /// <para>Returns an enumerator for the <see cref='System.Management.MethodDataCollection'/>.</para> /// </summary> /// <remarks> /// <para> Each call to this method /// returns a new enumerator on the collection. Multiple enumerators can be obtained /// for the same method collection. However, each enumerator takes a snapshot /// of the collection, so changes made to the collection after the enumerator was /// obtained are not reflected.</para> /// </remarks> /// <returns>An <see cref="System.Collections.IEnumerator"/> to enumerate through the collection.</returns> public MethodDataEnumerator GetEnumerator() { return new MethodDataEnumerator(parent); } //Enumerator class /// <summary> /// <para>Represents the enumerator for <see cref='System.Management.MethodData'/> /// objects in the <see cref='System.Management.MethodDataCollection'/>.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This sample demonstrates how to enumerate all methods in /// // Win32_LogicalDisk class using MethodDataEnumerator object. /// /// class Sample_MethodDataEnumerator /// { /// public static int Main(string[] args) /// { /// ManagementClass diskClass = new ManagementClass("win32_logicaldisk"); /// MethodDataCollection.MethodDataEnumerator diskEnumerator = /// diskClass.Methods.GetEnumerator(); /// while(diskEnumerator.MoveNext()) /// { /// MethodData method = diskEnumerator.Current; /// Console.WriteLine("Method = " + method.Name); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates how to enumerate all methods in /// ' Win32_LogicalDisk class using MethodDataEnumerator object. /// /// Class Sample_MethodDataEnumerator /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim diskClass As New ManagementClass("win32_logicaldisk") /// Dim diskEnumerator As _ /// MethodDataCollection.MethodDataEnumerator = _ /// diskClass.Methods.GetEnumerator() /// While diskEnumerator.MoveNext() /// Dim method As MethodData = diskEnumerator.Current /// Console.WriteLine("Method = " &amp; method.Name) /// End While /// Return 0 /// End Function /// End Class /// </code> /// </example> public class MethodDataEnumerator : IEnumerator { private ManagementObject parent; private ArrayList methodNames; //can't use simple array because we don't know the size... private IEnumerator en; //Internal constructor //Because WMI doesn't provide a "GetMethodNames" for methods similar to "GetNames" for properties, //We have to walk the methods list and cache the names here. //We lock to ensure that another thread doesn't interfere in the Begin/Next sequence. internal MethodDataEnumerator(ManagementObject parent) { this.parent = parent; methodNames = new ArrayList(); IWbemClassObjectFreeThreaded inP = null, outP = null; string tempMethodName; int status = (int)ManagementStatus.Failed; #pragma warning disable CA2002 lock(typeof(enumLock)) #pragma warning restore CA2002 { try { status = parent.wbemObject.BeginMethodEnumeration_(0); if (status >= 0) { tempMethodName = ""; // Condition primer to branch into the while loop. while (tempMethodName != null && status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA) { tempMethodName = null; status = parent.wbemObject.NextMethod_(0, out tempMethodName, out inP, out outP); if (status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA) methodNames.Add(tempMethodName); } parent.wbemObject.EndMethodEnumeration_(); // Ignore status. } } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } en = methodNames.GetEnumerator(); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } /// <internalonly/> object IEnumerator.Current { get { return (object)this.Current; } } /// <summary> /// <para>Returns the current <see cref='System.Management.MethodData'/> in the <see cref='System.Management.MethodDataCollection'/> /// enumeration.</para> /// </summary> /// <value>The current <see cref='System.Management.MethodData'/> item in the collection.</value> public MethodData Current { get { return new MethodData(parent, (string)en.Current); } } /// <summary> /// <para>Moves to the next element in the <see cref='System.Management.MethodDataCollection'/> enumeration.</para> /// </summary> /// <returns><see langword='true'/> if the enumerator was successfully advanced to the next method; <see langword='false'/> if the enumerator has passed the end of the collection.</returns> public bool MoveNext () { return en.MoveNext(); } /// <summary> /// <para>Resets the enumerator to the beginning of the <see cref='System.Management.MethodDataCollection'/> enumeration.</para> /// </summary> public void Reset() { en.Reset(); } }//MethodDataEnumerator // //Methods // /// <summary> /// <para>Returns the specified <see cref='System.Management.MethodData'/> from the <see cref='System.Management.MethodDataCollection'/>.</para> /// </summary> /// <param name='methodName'>The name of the method requested.</param> /// <value>A <see cref='System.Management.MethodData'/> instance containing all information about the specified method.</value> public virtual MethodData this[string methodName] { get { if (null == methodName) throw new ArgumentNullException (nameof(methodName)); return new MethodData(parent, methodName); } } /// <summary> /// <para>Removes a <see cref='System.Management.MethodData'/> from the <see cref='System.Management.MethodDataCollection'/>.</para> /// </summary> /// <param name='methodName'>The name of the method to remove from the collection.</param> /// <remarks> /// <para> /// Removing <see cref='System.Management.MethodData'/> objects from the <see cref='System.Management.MethodDataCollection'/> /// can only be done when the class has no /// instances. Any other case will result in an exception.</para> /// </remarks> public virtual void Remove(string methodName) { if (parent.GetType() == typeof(ManagementObject)) //can't remove methods from instance throw new InvalidOperationException(); int status = (int)ManagementStatus.Failed; try { status = parent.wbemObject.DeleteMethod_(methodName); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } //This variant takes only a method name and assumes a void method with no in/out parameters /// <overload> /// <para>Adds a <see cref='System.Management.MethodData'/> to the <see cref='System.Management.MethodDataCollection'/>.</para> /// </overload> /// <summary> /// <para>Adds a <see cref='System.Management.MethodData'/> to the <see cref='System.Management.MethodDataCollection'/>. This overload will /// add a new method with no parameters to the collection.</para> /// </summary> /// <param name='methodName'>The name of the method to add.</param> /// <remarks> /// <para> Adding <see cref='System.Management.MethodData'/> objects to the <see cref='System.Management.MethodDataCollection'/> can only /// be done when the class has no instances. Any other case will result in an /// exception.</para> /// </remarks> public virtual void Add(string methodName) { Add(methodName, null, null); } //This variant takes the full information, i.e. the method name and in & out param objects /// <summary> /// <para>Adds a <see cref='System.Management.MethodData'/> to the <see cref='System.Management.MethodDataCollection'/>. This overload will add a new method with the /// specified parameter objects to the collection.</para> /// </summary> /// <param name='methodName'>The name of the method to add.</param> /// <param name=' inParameters'>The <see cref='System.Management.ManagementBaseObject'/> holding the input parameters to the method.</param> /// <param name=' outParameters'>The <see cref='System.Management.ManagementBaseObject'/> holding the output parameters to the method.</param> /// <remarks> /// <para> Adding <see cref='System.Management.MethodData'/> objects to the <see cref='System.Management.MethodDataCollection'/> can only be /// done when the class has no instances. Any other case will result in an /// exception.</para> /// </remarks> public virtual void Add(string methodName, ManagementBaseObject inParameters, ManagementBaseObject outParameters) { IWbemClassObjectFreeThreaded wbemIn = null, wbemOut = null; if (parent.GetType() == typeof(ManagementObject)) //can't add methods to instance throw new InvalidOperationException(); if (inParameters != null) wbemIn = inParameters.wbemObject; if (outParameters != null) wbemOut = outParameters.wbemObject; int status = (int)ManagementStatus.Failed; try { status = parent.wbemObject.PutMethod_(methodName, 0, wbemIn, wbemOut); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } }//MethodDataCollection }
#region Copyright /*Copyright (C) 2015 Wosad Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Windows.Controls; using Dynamo.Controls; using Dynamo.Models; using Dynamo.Wpf; using ProtoCore.AST.AssociativeAST; using Wosad.Common.CalculationLogger; using Wosad.Dynamo.Common; using Wosad.Loads.ASCE7.Entities; using System.Xml; using GalaSoft.MvvmLight.CommandWpf; using System.Windows.Input; using System.Windows; using Wosad.Dynamo.Common.Infra.TreeItems; using Wosad.Dynamo.UI.Common.TreeItems; using Wosad.Dynamo.UI.Views.Loads.ASCE7_10; namespace Loads.ASCE7_10.Gravity.Snow { /// <summary> ///Thermal condition - ASCE7-10 /// </summary> [NodeName("Snow thermal case")] [NodeCategory("Wosad.Loads.ASCE7_10.Gravity.Snow")] [NodeDescription("Thermal condition - ASCE7-10")] [IsDesignScriptCompatible] public class SnowThermalCase : UiNodeBase { public SnowThermalCase() { ReportEntry=""; SnowThermalCaseId = "Regular structure"; OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)")); OutPortData.Add(new PortData("SnowThermalCaseDescription", "Snow thermal case description")); RegisterAllPorts(); //PropertyChanged += NodePropertyChanged; } /// <summary> /// Gets the type of this class, to be used in base class for reflection /// </summary> protected override Type GetModelType() { return GetType(); } #region properties #region InputProperties #endregion #region OutputProperties #region SnowThermalCaseProperty /// <summary> /// SnowThermalCase property /// </summary> /// <value>Snow thermal case</value> public string _SnowThermalCaseId; public string SnowThermalCaseId { get { return _SnowThermalCaseId; } set { _SnowThermalCaseId = value; RaisePropertyChanged("SnowThermalCaseId"); OnNodeModified(); } } #endregion #region SnowThermalCaseDescription Property private string liveLoadOccupancyDescription; public string SnowThermalCaseDescription { get { return liveLoadOccupancyDescription; } set { liveLoadOccupancyDescription = value; RaisePropertyChanged("SnowThermalCaseDescription"); } } #endregion #region ReportEntryProperty /// <summary> /// log property /// </summary> /// <value>Calculation entries that can be converted into a report.</value> public string reportEntry; public string ReportEntry { get { return reportEntry; } set { reportEntry = value; RaisePropertyChanged("ReportEntry"); OnNodeModified(); } } #endregion #endregion #endregion #region Serialization /// <summary> ///Saves property values to be retained when opening the node /// </summary> protected override void SerializeCore(XmlElement nodeElement, SaveContext context) { base.SerializeCore(nodeElement, context); nodeElement.SetAttribute("SnowThermalCase", SnowThermalCaseId); } /// <summary> ///Retrieved property values when opening the node /// </summary> protected override void DeserializeCore(XmlElement nodeElement, SaveContext context) { base.DeserializeCore(nodeElement, context); var attrib = nodeElement.Attributes["SnowThermalCase"]; if (attrib == null) return; this.SnowThermalCaseId = attrib.Value; } public void UpdateSelectionEvents() { if (TreeViewControl != null) { TreeViewControl.SelectedItemChanged += OnTreeViewSelectionChanged; } } private void OnTreeViewSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { OnSelectedItemChanged(e.NewValue); } private void SetCaseDescription() { Uri uri = new Uri("pack://application:,,,/Wosad.Dynamo.UI;component/Views/Loads/ASCE7_10/Snow/SnowThermalCase/SnowThermalCaseTreeData.xml"); XmlTreeHelper treeHelper = new XmlTreeHelper(); treeHelper.ExamineXmlTreeFile(uri, new EvaluateXmlNodeDelegate(FindDescription)); } private void FindDescription(XmlNode node) { //check if attribute "Id" exists if (null != node.Attributes["Tag"]) { if (node.Attributes["Tag"].Value== SnowThermalCaseId) { SnowThermalCaseDescription = node.Attributes["Description"].Value; } } } #endregion #region treeView elements public TreeView TreeViewControl { get; set; } private ICommand selectedItemChanged; public ICommand SelectedItemChanged { get { if (SnowThermalCaseDescription == null) { selectedItemChanged = new RelayCommand<object>((i) => { OnSelectedItemChanged(i); }); } return selectedItemChanged; } } public void DisplayComponentUI(XTreeItem selectedComponent) { //Example of parsing a string and creating a control from a string //if (selectedComponent != null && selectedComponent.Tag != "X" && selectedComponent.ResourcePath != null) //{ // Assembly execAssembly = Assembly.GetExecutingAssembly(); // AssemblyName assemblyName = new AssemblyName(execAssembly.FullName); // string execAssemblyName = assemblyName.Name; // string typeStr =execAssemblyName +".Views.Loads.ASCE7_10." + selectedComponent.ResourcePath; // try // { // Type subMenuType = execAssembly.GetType(typeStr); // UserControl subMenu = (UserControl)Activator.CreateInstance(subMenuType); // AdditionalUI = subMenu; // if (selectedComponent.Id != "X") //parse default values // { // int ind1, ind2; // double numeric; // string DefaultValues = selectedComponent.Id; // string[] Vals = DefaultValues.Split(','); // if (Vals.Length == 3) // { // bool ind1Res = int.TryParse(Vals[0], out ind1); if (ind1Res == true) ComponentOption1 = ind1; // bool ind2Res = int.TryParse(Vals[1], out ind2); if (ind2Res == true) ComponentOption2 = ind2; // bool numRes = double.TryParse(Vals[2], out numeric); if (numRes == true) ComponentValue = numeric; // } // else // { // ComponentOption1 = -1; // ComponentOption2 = -1; // ComponentValue = 0; // } // } // } // catch (Exception) // { // AdditionalUI = null; // } //} //else //{ // AdditionalUI = null; //} } private XTreeItem selectedItem; public XTreeItem SelectedItem { get { return selectedItem; } set { selectedItem = value; } } private void OnSelectedItemChanged(object i) { XmlElement item = i as XmlElement; XTreeItem xtreeItem = new XTreeItem() { // PropertyName = item.GetAttribute("XmlTag"), }; if (item != null) { //Example //string id =xtreeItem.Tag; //if (id != "X") //{ //SnowThermalCaseId = id; //SnowThermalCaseDescription = xtreeItem.Description; //SelectedItem = xtreeItem; //DisplayComponentUI(xtreeItem); //} } } #endregion //Additional UI is a user control which is based on the user selection // can remove this property #region Additional UI private UserControl additionalUI; public UserControl AdditionalUI { get { return additionalUI; } set { additionalUI = value; RaisePropertyChanged("AdditionalUI"); } } #endregion /// <summary> ///Customization of WPF view in Dynamo UI /// </summary> public class SnowThermalCaseViewCustomization : UiNodeBaseViewCustomization, INodeViewCustomization<SnowThermalCase> { public void CustomizeView(SnowThermalCase model, NodeView nodeView) { base.CustomizeView(model, nodeView); SnowThermalCaseView control = new SnowThermalCaseView(); control.DataContext = model; //remove this part if control does not contain tree TreeView tv = control.FindName("selectionTree") as TreeView; if (tv!=null) { model.TreeViewControl = tv; model.UpdateSelectionEvents(); } nodeView.inputGrid.Children.Add(control); base.CustomizeView(model, nodeView); } } } }
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 Rainy.ClientService.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>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <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 factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private 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 to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified 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) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), 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="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <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, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [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; } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.Threading; using System.Reflection; using System.Collections.Generic; namespace System.Abstract { /// <summary> /// DefaultServiceCacheRegistrationDispatcher /// </summary> public class DefaultServiceCacheRegistrationDispatcher : ServiceCacheRegistration.IDispatcher { private static readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim(); /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public T Get<T>(IServiceCache cache, IServiceCacheRegistration registration, object tag, object[] values) { if (cache == null) throw new ArgumentNullException("cache"); if (registration == null) throw new ArgumentNullException("registration"); var registration2 = (registration as ServiceCacheRegistration); if (registration2 == null) throw new ArgumentException("must be ServiceCacheRegistration", "registration"); var itemPolicy = registration2.ItemPolicy; if (itemPolicy == null) throw new ArgumentNullException("registration.ItemPolicy"); // fetch from cache var name = registration.AbsoluteName; string @namespace; if (values != null && values.Length > 0) cache = cache.BehaveAs(values, out @namespace); else @namespace = null; var useDBNull = ((cache.Settings.Options & ServiceCacheOptions.UseDBNullWithRegistrations) == ServiceCacheOptions.UseDBNullWithRegistrations); var distributedServiceCache = cache.BehaveAs<IDistributedServiceCache>(); if (distributedServiceCache == null) return GetUsingLock<T>(cache, registration2, tag, values, name, @namespace, useDBNull); return GetUsingCas<T>(distributedServiceCache, registration2, tag, values, name, @namespace, useDBNull); } /// <summary> /// Sends the specified cache. /// </summary> /// <param name="cache">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="messages">The messages.</param> public void Send(IServiceCache cache, IServiceCacheRegistration registration, object tag, params object[] messages) { if (cache == null) throw new ArgumentNullException("cache"); if (registration == null) throw new ArgumentNullException("registration"); var registration2 = (registration as ServiceCacheRegistration); if (registration2 == null) throw new ArgumentException("must be ServiceCacheRegistration", "registration"); var itemPolicy = registration2.ItemPolicy; if (itemPolicy == null) throw new ArgumentNullException("registration.ItemPolicy"); var handlerInfos = registration2.GetHandlersFor(messages); if (!handlerInfos.GetEnumerator().MoveNext()) return; foreach (var header in cache.Get(tag, registration)) foreach (var handlerInfo in handlerInfos) handlerInfo.ConsumerInvoke(_handlerContextInfos, cache, registration, tag, header); } /// <summary> /// Queries the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="messages">The messages.</param> /// <returns></returns> public IEnumerable<T> Query<T>(IServiceCache cache, IServiceCacheRegistration registration, object tag, params object[] messages) { if (cache == null) throw new ArgumentNullException("cache"); if (registration == null) throw new ArgumentNullException("registration"); var registration2 = (registration as ServiceCacheRegistration); if (registration2 == null) throw new ArgumentException("must be ServiceCacheRegistration", "registration"); var itemPolicy = registration2.ItemPolicy; if (itemPolicy == null) throw new ArgumentNullException("registration.ItemPolicy"); var handlerInfos = registration2.GetHandlersFor(messages); if (!handlerInfos.GetEnumerator().MoveNext()) yield break; foreach (var header in cache.Get(tag, registration)) foreach (var handlerInfo in handlerInfos) yield return (T)handlerInfo.QueryInvoke(_handlerContextInfos, cache, registration, tag, header); } /// <summary> /// Removes the specified cache. /// </summary> /// <param name="cache">The cache.</param> /// <param name="registration">The registration.</param> public void Remove(IServiceCache cache, IServiceCacheRegistration registration) { if (cache == null) throw new ArgumentNullException("cache"); if (registration == null) throw new ArgumentNullException("registration"); var registration2 = (registration as ServiceCacheRegistration); if (registration2 == null) throw new ArgumentException("must be ServiceCacheRegistration", "registration"); foreach (var name in registration2.Keys) cache.Remove(null, name, registration); } private static T CreateData<T>(string @namespace, ServiceCacheRegistration registration, object tag, object[] values, out CacheItemHeader header) { if (@namespace != null) { var namespaces = (List<string>)registration.Namespaces; if (!namespaces.Contains(@namespace)) namespaces.Add(@namespace); } header = new CacheItemHeader { Values = values, }; return (T)registration.Builder(tag, values); } #region HandlerContext private static MethodInfo[] _handlerContextInfos = new[] { typeof(DefaultServiceCacheRegistrationDispatcher).GetMethod("HandlerContextGet", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly), typeof(DefaultServiceCacheRegistrationDispatcher).GetMethod("HandlerContextUpdate", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly) }; private static T HandlerContextGet<T>(IServiceCache cache, IServiceCacheRegistration registration, object tag, CacheItemHeader header) { var v = cache.Get(null, header.Item); return (v is T ? (T)v : default(T)); } private static void HandlerContextUpdate<T>(IServiceCache cache, IServiceCacheRegistration registration, object tag, CacheItemHeader header, object value) { var registration2 = (registration as ServiceCacheRegistration); var useDBNull = ((cache.Settings.Options & ServiceCacheOptions.UseDBNullWithRegistrations) == ServiceCacheOptions.UseDBNullWithRegistrations); var distributedServiceCache = cache.BehaveAs<IDistributedServiceCache>(); if (distributedServiceCache == null) SetUsingLock(cache, registration2, tag, header, useDBNull, value); else SetUsingCas(distributedServiceCache, registration2, tag, header, useDBNull, value); } #endregion #region Locks private static T GetUsingNoLock<T>(IServiceCache cache, ServiceCacheRegistration registration, object tag, object[] values, string name, string @namespace, bool useDBNull) { CacheItemHeader header; var valueAsCache = cache.Get(tag, name, registration, out header); if (valueAsCache != null && (!registration.UseHeaders || header != null)) return (!useDBNull || !(valueAsCache is DBNull) ? (T)valueAsCache : default(T)); // create var value = CreateData<T>(@namespace, registration, tag, values, out header); valueAsCache = (!useDBNull || value != null ? (object)value : DBNull.Value); cache.Add(tag, name, registration.ItemPolicy, valueAsCache, new ServiceCacheByDispatcher(registration, values, header)); return value; } private static void SetUsingNoLock(IServiceCache cache, ServiceCacheRegistration registration, object tag, CacheItemHeader header, bool useDBNull, object value) { var valueAsCache = (!useDBNull || value != null ? (object)value : DBNull.Value); cache.Add(tag, header.Item, registration.ItemPolicy, valueAsCache, new ServiceCacheByDispatcher(registration, header.Values, header)); } private static T GetUsingLock<T>(IServiceCache cache, ServiceCacheRegistration registration, object tag, object[] values, string name, string @namespace, bool useDBNull) { CacheItemHeader header; var valueAsCache = cache.Get(tag, name, registration, out header); if (valueAsCache != null && (!registration.UseHeaders || header != null)) return (!useDBNull || !(valueAsCache is DBNull) ? (T)valueAsCache : default(T)); lock (_rwLock) { valueAsCache = cache.Get(tag, name, registration, out header); if (valueAsCache != null && (!registration.UseHeaders || header != null)) return (!useDBNull || !(valueAsCache is DBNull) ? (T)valueAsCache : default(T)); // create var value = CreateData<T>(@namespace, registration, tag, values, out header); valueAsCache = (!useDBNull || value != null ? (object)value : DBNull.Value); cache.Add(tag, name, registration.ItemPolicy, valueAsCache, new ServiceCacheByDispatcher(registration, values, header)); return value; } } private static void SetUsingLock(IServiceCache cache, ServiceCacheRegistration registration, object tag, CacheItemHeader header, bool useDBNull, object value) { lock (_rwLock) { var valueAsCache = (!useDBNull || value != null ? (object)value : DBNull.Value); cache.Add(tag, header.Item, registration.ItemPolicy, valueAsCache, new ServiceCacheByDispatcher(registration, header.Values, header)); } } private static T GetUsingRwLock<T>(IServiceCache cache, ServiceCacheRegistration registration, object tag, object[] values, string name, string @namespace, bool useDBNull) { _rwLock.EnterUpgradeableReadLock(); try { CacheItemHeader header; var valueAsCache = cache.Get(tag, name, registration, out header); if (valueAsCache != null && (!registration.UseHeaders || header != null)) return (!useDBNull || !(valueAsCache is DBNull) ? (T)valueAsCache : default(T)); _rwLock.EnterWriteLock(); try { valueAsCache = cache.Get(tag, name, registration, out header); if (valueAsCache != null && (!registration.UseHeaders || header != null)) return (!useDBNull || !(valueAsCache is DBNull) ? (T)valueAsCache : default(T)); // create var value = CreateData<T>(@namespace, registration, tag, values, out header); valueAsCache = (!useDBNull || value != null ? (object)value : DBNull.Value); cache.Add(tag, name, registration.ItemPolicy, valueAsCache, new ServiceCacheByDispatcher(registration, values, header)); return value; } finally { _rwLock.ExitWriteLock(); } } finally { _rwLock.ExitUpgradeableReadLock(); } } private static void SetUsingRwLock(IServiceCache cache, ServiceCacheRegistration registration, object tag, CacheItemPolicy itemPolicy, CacheItemHeader header, bool useDBNull, object value) { _rwLock.EnterWriteLock(); try { var valueAsCache = (!useDBNull || value != null ? (object)value : DBNull.Value); cache.Add(tag, header.Item, itemPolicy, valueAsCache, new ServiceCacheByDispatcher(registration, header.Values, header)); } finally { _rwLock.ExitWriteLock(); } } private static T GetUsingCas<T>(IDistributedServiceCache cache, ServiceCacheRegistration registration, object tag, object[] values, string name, string @namespace, bool useDBNull) { CacheItemHeader header; var valueAsCache = cache.Get(tag, name, registration, out header); if (valueAsCache != null && (!registration.UseHeaders || header != null)) return (!useDBNull || !(valueAsCache is DBNull) ? (T)valueAsCache : default(T)); // create var value = CreateData<T>(@namespace, registration, tag, values, out header); valueAsCache = (!useDBNull || value != null ? (object)value : DBNull.Value); cache.Add(tag, name, registration.ItemPolicy, valueAsCache, new ServiceCacheByDispatcher(registration, values, header)); return value; } private static void SetUsingCas(IDistributedServiceCache cache, ServiceCacheRegistration registration, object tag, CacheItemHeader header, bool useDBNull, object value) { var valueAsCache = (!useDBNull || value != null ? (object)value : DBNull.Value); cache.Add(tag, header.Item, registration.ItemPolicy, valueAsCache, new ServiceCacheByDispatcher(registration, header.Values, header)); } #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace fastJSON { /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// </summary> internal sealed class JsonParser { enum Token { None = -1, // Used to denote no Lookahead available Curly_Open, Curly_Close, Squared_Open, Squared_Close, Colon, Comma, String, Number, True, False, Null } readonly string json; readonly StringBuilder s = new StringBuilder(); // used for inner string parsing " \"\r\n\u1234\'\t " Token lookAheadToken = Token.None; int index; internal JsonParser(string json) { this.json = json; } public object Decode() { return ParseValue(); } private Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); ConsumeToken(); // { while (true) { switch (LookAhead()) { case Token.Comma: ConsumeToken(); break; case Token.Curly_Close: ConsumeToken(); return table; default: { // name string name = ParseString(); // : if (NextToken() != Token.Colon) { throw new Exception("Expected colon at index " + index); } // value object value = ParseValue(); table[name] = value; } break; } } } private List<object> ParseArray() { List<object> array = new List<object>(); ConsumeToken(); // [ while (true) { switch (LookAhead()) { case Token.Comma: ConsumeToken(); break; case Token.Squared_Close: ConsumeToken(); return array; default: array.Add(ParseValue()); break; } } } private object ParseValue() { switch (LookAhead()) { case Token.Number: return ParseNumber(); case Token.String: return ParseString(); case Token.Curly_Open: return ParseObject(); case Token.Squared_Open: return ParseArray(); case Token.True: ConsumeToken(); return true; case Token.False: ConsumeToken(); return false; case Token.Null: ConsumeToken(); return null; } throw new Exception("Unrecognized token at index" + index); } private string ParseString() { ConsumeToken(); // " s.Length = 0; int runIndex = -1; while (index < json.Length) { var c = json[index++]; if (c == '"') { if (runIndex != -1) { if (s.Length == 0) return json.Substring(runIndex, index - runIndex - 1); s.Append(json, runIndex, index - runIndex - 1); } return s.ToString(); } if (c != '\\') { if (runIndex == -1) runIndex = index - 1; continue; } if (index == json.Length) break; if (runIndex != -1) { s.Append(json, runIndex, index - runIndex - 1); runIndex = -1; } switch (json[index++]) { case '"': s.Append('"'); break; case '\\': s.Append('\\'); break; case '/': s.Append('/'); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': { int remainingLength = json.Length - index; if (remainingLength < 4) break; // parse the 32 bit hex into an integer codepoint uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]); s.Append((char)codePoint); // skip 4 chars index += 4; } break; } } throw new Exception("Unexpectedly reached end of string"); } private uint ParseSingleChar(char c1, uint multipliyer) { uint p1 = 0; if (c1 >= '0' && c1 <= '9') p1 = (uint)(c1 - '0') * multipliyer; else if (c1 >= 'A' && c1 <= 'F') p1 = (uint)((c1 - 'A') + 10) * multipliyer; else if (c1 >= 'a' && c1 <= 'f') p1 = (uint)((c1 - 'a') + 10) * multipliyer; return p1; } private uint ParseUnicode(char c1, char c2, char c3, char c4) { uint p1 = ParseSingleChar(c1, 0x1000); uint p2 = ParseSingleChar(c2, 0x100); uint p3 = ParseSingleChar(c3, 0x10); uint p4 = ParseSingleChar(c4, 1); return p1 + p2 + p3 + p4; } private long CreateLong(string s) { long num = 0; bool neg = false; foreach (char cc in s) { if (cc == '-') neg = true; else if (cc == '+') neg = false; else { num *= 10; num += (int)(cc - '0'); } } return neg ? -num : num; } private object ParseNumber() { ConsumeToken(); // Need to start back one place because the first digit is also a token and would have been consumed var startIndex = index - 1; bool dec = false; do { if (index == json.Length) break; var c = json[index]; if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E') { if (c == '.' || c == 'e' || c == 'E') dec = true; if (++index == json.Length) break;//throw new Exception("Unexpected end of string whilst parsing number"); continue; } break; } while (true); if (dec) { string s = json.Substring(startIndex, index - startIndex); return double.Parse(s, NumberFormatInfo.InvariantInfo); } return JSON.CreateLong(json, startIndex, index - startIndex); } private Token LookAhead() { if (lookAheadToken != Token.None) return lookAheadToken; return lookAheadToken = NextTokenCore(); } private void ConsumeToken() { lookAheadToken = Token.None; } private Token NextToken() { var result = lookAheadToken != Token.None ? lookAheadToken : NextTokenCore(); lookAheadToken = Token.None; return result; } private Token NextTokenCore() { char c; // Skip past whitespace do { c = json[index]; if (c == '/' && json[index + 1] == '/') // c++ style single line comments { index++; index++; do { c = json[index]; if (c == '\r' || c == '\n') break; // read till end of line } while (++index < json.Length); } if (c > ' ') break; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; } while (++index < json.Length); if (index == json.Length) { throw new Exception("Reached end of string unexpectedly"); } c = json[index]; index++; switch (c) { case '{': return Token.Curly_Open; case '}': return Token.Curly_Close; case '[': return Token.Squared_Open; case ']': return Token.Squared_Close; case ',': return Token.Comma; case '"': return Token.String; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': case '+': case '.': return Token.Number; case ':': return Token.Colon; case 'f': if (json.Length - index >= 4 && json[index + 0] == 'a' && json[index + 1] == 'l' && json[index + 2] == 's' && json[index + 3] == 'e') { index += 4; return Token.False; } break; case 't': if (json.Length - index >= 3 && json[index + 0] == 'r' && json[index + 1] == 'u' && json[index + 2] == 'e') { index += 3; return Token.True; } break; case 'n': if (json.Length - index >= 3 && json[index + 0] == 'u' && json[index + 1] == 'l' && json[index + 2] == 'l') { index += 3; return Token.Null; } break; } throw new Exception("Could not find token at index " + --index); } } }
// *********************************************************************** // Copyright (c) 2014-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework.Interfaces; namespace NUnitLite { /// <summary> /// Helper class used to summarize the result of a test run /// </summary> public class ResultSummary { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ResultSummary"/> class. /// </summary> /// <param name="result">The result.</param> public ResultSummary(ITestResult result) { InitializeCounters(); ResultState = result.ResultState; StartTime = result.StartTime; EndTime = result.EndTime; Duration = result.Duration; Summarize(result); } #endregion #region Properties /// <summary> /// Gets the number of test cases for which results /// have been summarized. Any tests excluded by use of /// Category or Explicit attributes are not counted. /// </summary> public int TestCount { get; private set; } /// <summary> /// Returns the number of test cases actually run. /// </summary> public int RunCount { get { return PassCount + ErrorCount + FailureCount + InconclusiveCount; } } /// <summary> /// Gets the number of tests not run for any reason. /// </summary> public int NotRunCount { get { return InvalidCount + SkipCount + IgnoreCount + ExplicitCount; } } /// <summary> /// Returns the number of failed test cases (including errors and invalid tests) /// </summary> public int FailedCount { get { return FailureCount + InvalidCount + ErrorCount; } } /// <summary> /// Returns the sum of skipped test cases, including ignored and explicit tests /// </summary> public int TotalSkipCount { get { return SkipCount + IgnoreCount + ExplicitCount; } } /// <summary> /// Gets the count of passed tests /// </summary> public int PassCount { get; private set; } /// <summary> /// Gets count of failed tests, excluding errors and invalid tests /// </summary> public int FailureCount { get; private set; } /// <summary> /// Gets the error count /// </summary> public int ErrorCount { get; private set; } /// <summary> /// Gets the count of inconclusive tests /// </summary> public int InconclusiveCount { get; private set; } /// <summary> /// Returns the number of test cases that were not runnable /// due to errors in the signature of the class or method. /// Such tests are also counted as Errors. /// </summary> public int InvalidCount { get; private set; } /// <summary> /// Gets the count of skipped tests, excluding ignored tests /// </summary> public int SkipCount { get; private set; } /// <summary> /// Gets the ignore count /// </summary> public int IgnoreCount { get; private set; } /// <summary> /// Gets the explicit count /// </summary> public int ExplicitCount { get; private set; } /// <summary> /// Invalid Test Fixtures /// </summary> public int InvalidTestFixtures { get; private set; } /// <summary> /// Gets the ResultState of the test result, which /// indicates the success or failure of the test. /// </summary> public ResultState ResultState { get; private set; } /// <summary> /// Gets or sets the time the test started running. /// </summary> public DateTime StartTime { get; private set; } /// <summary> /// Gets or sets the time the test finished running. /// </summary> public DateTime EndTime { get; private set; } /// <summary> /// Gets or sets the elapsed time for running the test in seconds /// </summary> public double Duration { get; private set; } #endregion #region Helper Methods private void InitializeCounters() { TestCount = 0; PassCount = 0; FailureCount = 0; ErrorCount = 0; InconclusiveCount = 0; SkipCount = 0; IgnoreCount = 0; ExplicitCount = 0; InvalidCount = 0; } private void Summarize(ITestResult result) { var label = result.ResultState.Label; var status = result.ResultState.Status; if (result.Test.IsSuite) { if (status == TestStatus.Failed && label == "Invalid") InvalidTestFixtures++; foreach (ITestResult r in result.Children) Summarize(r); } else { TestCount++; switch (status) { case TestStatus.Passed: PassCount++; break; case TestStatus.Skipped: if (label == "Ignored") IgnoreCount++; else if (label == "Explicit") ExplicitCount++; else SkipCount++; break; case TestStatus.Failed: if (label == "Invalid") InvalidCount++; else if (label == "Error") ErrorCount++; else FailureCount++; break; case TestStatus.Inconclusive: InconclusiveCount++; break; } return; } } #endregion } }
// ReSharper disable InconsistentNaming using System; using System.Text; using System.Threading; using EasyNetQ.Loggers; using EasyNetQ.Topology; using NUnit.Framework; namespace EasyNetQ.Tests.Integration { [TestFixture] public class PublishSubscribeTests { private IBus bus; [SetUp] public void SetUp() { bus = RabbitHutch.CreateBus("host=localhost"); while(!bus.IsConnected) Thread.Sleep(10); } [TearDown] public void TearDown() { if(bus != null) bus.Dispose(); } // 1. Run this first, should see no messages consumed // 3. Run this again (after publishing below), should see published messages appear [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_subscribe() { var autoResetEvent = new AutoResetEvent(false); bus.Subscribe<MyMessage>("test", message => { Console.WriteLine(message.Text); autoResetEvent.Set(); }); // allow time for messages to be consumed autoResetEvent.WaitOne(1000); Console.WriteLine("Stopped consuming"); } [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_subscribe_as_exlusive() { var countdownEvent = new CountdownEvent(10); var firstCount = 0; var secondCount = 0; bus.Subscribe<MyMessage>("test", message => { countdownEvent.Signal(); Interlocked.Increment(ref firstCount); Console.WriteLine("[1] " + message.Text); }, x => x.AsExclusive()); bus.Subscribe<MyMessage>("test", message => { countdownEvent.Signal(); Interlocked.Increment(ref secondCount); Console.WriteLine("[2] " + message.Text); }, x => x.AsExclusive()); for (var i = 0; i < 10; ++i) bus.Publish(new MyMessage { Text = "Exclusive " + i }); countdownEvent.Wait(10 * 1000); Assert.IsTrue(firstCount == 10 && secondCount == 0 || firstCount == 0 && secondCount == 10); Console.WriteLine("Stopped consuming"); } [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Long_running_exclusive_subscriber_should_survive_a_rabbit_restart() { var autoResetEvent = new AutoResetEvent(false); bus.Subscribe<MyMessage>("test", message => { Console.Out.WriteLine("Restart RabbitMQ now."); new Timer(x => { Console.WriteLine(message.Text); autoResetEvent.Set(); }, null, 5000, Timeout.Infinite); }, x => x.AsExclusive()); // allow time for messages to be consumed autoResetEvent.WaitOne(15000); Console.WriteLine("Stopped consuming"); } // 2. Run this a few times, should publish some messages [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_publish() { var message = new MyMessage { Text = "Hello! " + Guid.NewGuid().ToString().Substring(0, 5) }; bus.Publish(message); Console.Out.WriteLine("message.Text = {0}", message.Text); } // 4. Run this once to setup subscription, publish a few times using '2' above, run again to // see messages appear. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_also_send_messages_to_second_subscriber() { var autoResetEvent = new AutoResetEvent(false); var messageQueue2 = RabbitHutch.CreateBus("host=localhost"); messageQueue2.Subscribe<MyMessage>("test2", msg => { Console.WriteLine(msg.Text); autoResetEvent.Set(); }); // allow time for messages to be consumed autoResetEvent.WaitOne(500); Console.WriteLine("Stopped consuming"); } // 5. Run this once to setup subscriptions, publish a few times using '2' above, run again. // You should see two lots messages [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_two_subscriptions_from_the_same_app_should_also_both_get_all_messages() { var countdownEvent = new CountdownEvent(8); bus.Subscribe<MyMessage>("test_a", msg => { Console.WriteLine(msg.Text); countdownEvent.Signal(); }); bus.Subscribe<MyOtherMessage>("test_b", msg => { Console.WriteLine(msg.Text); countdownEvent.Signal(); }); bus.Subscribe<MyMessage>("test_c", msg => { Console.WriteLine(msg.Text); countdownEvent.Signal(); }); bus.Subscribe<MyOtherMessage>("test_d", msg => { Console.WriteLine(msg.Text); countdownEvent.Signal(); }); bus.Publish(new MyMessage { Text = "Hello! " + Guid.NewGuid().ToString().Substring(0, 5) }); bus.Publish(new MyMessage { Text = "Hello! " + Guid.NewGuid().ToString().Substring(0, 5) }); bus.Publish(new MyOtherMessage { Text = "Hello other! " + Guid.NewGuid().ToString().Substring(0, 5) }); bus.Publish(new MyOtherMessage { Text = "Hello other! " + Guid.NewGuid().ToString().Substring(0, 5) }); // allow time for messages to be consumed countdownEvent.Wait(1000); Console.WriteLine("Stopped consuming"); } // 6. Run publish first using '2' above. // 7. Run this test, while it's running, restart the RabbitMQ service. // [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Long_running_subscriber_should_survive_a_rabbit_restart() { var autoResetEvent = new AutoResetEvent(false); bus.Subscribe<MyMessage>("test", message => { Console.Out.WriteLine("Restart RabbitMQ now."); new Timer(x => { Console.WriteLine(message.Text); autoResetEvent.Set(); }, null, 5000, Timeout.Infinite); }); // allow time for messages to be consumed autoResetEvent.WaitOne(7000); Console.WriteLine("Stopped consuming"); } [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_subscribe_OK_before_connection_to_broker_is_complete() { var autoResetEvent = new AutoResetEvent(false); var testLocalBus = RabbitHutch.CreateBus("host=localhost"); testLocalBus.Subscribe<MyMessage>("test", message => { Console.Out.WriteLine("message.Text = {0}", message.Text); autoResetEvent.Set(); }); Console.WriteLine("--- subscribed ---"); // allow time for bus to connect autoResetEvent.WaitOne(1000); testLocalBus.Dispose(); } [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_round_robin_between_subscribers() { Action<IServiceRegister> setNoDebugLogger = register => register.Register<IEasyNetQLogger>(_ => new DelegateLogger()); const string connectionString = "host=localhost;prefetchcount=100"; var publishBus = RabbitHutch.CreateBus(connectionString, setNoDebugLogger); var subscribeBus1 = RabbitHutch.CreateBus(connectionString, setNoDebugLogger); var subscribeBus2 = RabbitHutch.CreateBus(connectionString, setNoDebugLogger); // first set up the subscribers subscribeBus1.Subscribe<MyMessage>("roundRobinTest", message => Console.WriteLine("Subscriber 1: {0}", message.Text)); subscribeBus2.Subscribe<MyMessage>("roundRobinTest", message => Console.WriteLine("Subscriber 2: {0}", message.Text)); // now publish some messages for (int i = 0; i < 50; i++) { publishBus.Publish(new MyMessage { Text = string.Format("Message{0}", i) }); } Thread.Sleep(1000); publishBus.Dispose(); subscribeBus1.Dispose(); subscribeBus2.Dispose(); } public static void SetImmediateToTrue() { var bus = RabbitHutch.CreateBus("host=localhost"); var properties = new MessageProperties(); var body = Encoding.UTF8.GetBytes("Test"); var message = new Message<MyMessage>(new MyMessage() { Text = "Hello" }); bus.Advanced.Publish(Exchange.GetDefault(), "test_queue", true, true, message); //bus.Advanced.Publish(Exchange.GetDefault(), "test_queue", true, true, properties, body); bus.Dispose(); } } } // ReSharper restore InconsistentNaming
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; namespace Revit.SDK.Samples.Openings.CS { /// <summary> /// Point class use to store point coordinate value /// and get the value via (x, y ,z)property /// </summary> public struct Vector { /// <summary> /// x coordinate of vector /// </summary> private double m_x; /// <summary> /// y coordinate of vector /// </summary> private double m_y; /// <summary> /// z coordinate of vector /// </summary> private double m_z; /// <summary> /// Property to get X coordinate /// </summary> public double X { get { return m_x; } set { m_x = value; } } /// <summary> /// Property to get Y coordinate /// </summary> public double Y { get { return m_y; } set { m_y = value; } } /// <summary> /// Property to get Z coordinate /// </summary> public double Z { get { return m_z; } set { m_z = value; } } /// <summary> /// Property to get x, y, z coordinate bu index 1, 2, 3 /// </summary> public double this[int index] { get { switch (index) { case 0: return m_x; case 1: return m_y; case 2: return m_z; default: throw new ArgumentOutOfRangeException(); } } set { switch (index) { case 0: m_x = value; break; case 1: m_y = value; break; case 2: m_z = value; break; default: throw new ArgumentOutOfRangeException(); } } } /// <summary> /// copy constructor /// </summary> public Vector(Vector rhs) { m_x = rhs.X; m_y = rhs.Y; m_z = rhs.Z; } /// <summary> /// constructor /// </summary> /// <param name="x">x coordinate of point</param> /// <param name="y">y coordinate of point</param> /// <param name="z">z coordinate of point</param> public Vector(double x, double y, double z) { m_x = x; m_y = y; m_z = z; } /// <summary> /// get Normal by vector /// </summary> public Vector GetNormal() { Vector direct = new Vector(); double len = GetLength(); direct.X = m_x / len; direct.Y = m_y / len; direct.Z = m_z / len; return direct; } /// <summary> /// add two vector /// </summary> /// <param name="lhs">first vector</param> /// <param name="rhs">second vector</param> /// <returns>add two vector</returns> public static Vector operator +(Vector lhs, Vector rhs) { Vector result = new Vector(lhs); result.X += rhs.X; result.Y += rhs.Y; result.Z += rhs.Z; return result; } /// <summary> /// subtraction of two vector /// </summary> /// <param name="lhs">first vector</param> /// <param name="rhs">second vector</param> /// <returns>subtraction of two vector</returns> public static Vector operator -(Vector lhs, Vector rhs) { Vector result = new Vector(lhs); result.X -= rhs.X; result.Y -= rhs.Y; result.Z -= rhs.Z; return result; } /// <summary> /// negative of vector /// </summary> /// <param name="lhs">vector</param> /// <returns>negative of vector</returns> public static Vector operator -(Vector lhs) { Vector result = new Vector(lhs); result.X = -lhs.X; result.Y = -lhs.Y; result.Z = -lhs.Z; return result; } /// <summary> /// get normal vector of two vector /// </summary> /// <param name="lhs">first vector</param> /// <param name="rhs">second vector</param> /// <returns> normal vector of two vector</returns> public static Vector operator &(Vector lhs, Vector rhs) { double v1 = lhs.X; double v2 = lhs.Y; double v3 = lhs.Z; double u1 = rhs.X; double u2 = rhs.Y; double u3 = rhs.Z; double x = v2 * u3 - v3 * u2; double y = v3 * u1 - v1 * u3; double z = v1 * u2 - v2 * u1; return new Vector(x, y, z); } /// <summary> /// get cross vector of two vector /// </summary> /// <param name="lhs">first vector</param> /// <param name="rhs">second vector</param> /// <returns> cross vector of two vector</returns> public static double operator *(Vector lhs, Vector rhs) { return lhs.X * rhs.X + lhs.Y * rhs.Y + lhs.Z * rhs.Z; } /// <summary> /// get vector multiply by an double value /// </summary> /// <param name="lhs">vector</param> /// <param name="rhs">double value</param> /// <returns> vector multiply by an double value</returns> public static Vector operator *(Vector lhs, double rhs) { return new Vector(lhs.X * rhs, lhs.Y * rhs, lhs.Z * rhs); } /// <summary> /// estimate whether two are unequal /// </summary> /// <param name="lhs">first vector</param> /// <param name="rhs">second vector</param> /// <returns> whether two are unequal</returns> public static bool operator !=(Vector lhs, Vector rhs) { return !IsEqual(lhs, rhs); } /// <summary> /// estimate whether two are equal /// </summary> /// <param name="lhs">first vector</param> /// <param name="rhs">second vector</param> /// <returns> whether two are equal</returns> public static bool operator ==(Vector lhs, Vector rhs) { return IsEqual(lhs, rhs); } /// <summary> /// get the length of vector /// </summary> /// <param name="lhs">vector</param> /// <returns>length of vector</returns> public static double operator ~(Vector lhs) { return lhs.GetLength(); } /// <summary> /// get vector divided by an double value /// </summary> /// <param name="lhs">vector</param> /// <param name="rhs">double value</param> /// <returns> vector divided by an double value</returns> public static Vector operator /(Vector lhs, double rhs) { return new Vector(lhs.m_x / rhs, lhs.m_y / rhs, lhs.m_z / rhs); } /// <summary> /// get angle of two vector /// </summary> /// <param name="lhs">first vector</param> /// <param name="rhs">second vector</param> /// <returns> angle of two vector</returns> public static double GetAngleOf2Vectors(Vector lhs, Vector rhs, bool acuteAngleDesired) { double angle = Math.Acos(lhs.GetNormal() * rhs.GetNormal()); if (acuteAngleDesired && angle > Math.PI / 2) { angle = Math.PI - angle; } return angle; } /// <summary> /// estimate whether two are equal /// </summary> /// <param name="obj">object which compare with</param> /// <returns> whether two are equal</returns> public override bool Equals(object obj) { try { Vector rhs = (Vector)obj; return IsEqual(this, rhs); } catch { } return false; } /// <summary> /// Get HashCode /// </summary> public override int GetHashCode() { return m_x.GetHashCode() ^ m_y.GetHashCode() ^ m_z.GetHashCode(); } /// <summary> /// Get Length of vector /// </summary> public double GetLength() { return Math.Sqrt(m_x*m_x + m_y*m_y + m_z*m_z); } /// <summary> /// estimate whether two vector are equal /// </summary> /// <param name="lhs">first vector</param> /// <param name="rhs">second vector</param> /// <returns> whether two are equal</returns> private static bool IsEqual(Vector lhs, Vector rhs) { if (lhs.X == rhs.X && lhs.X == rhs.X && lhs.X == rhs.X) { return true; } else { return false; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Compute { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Resource; /// <summary> /// Compute task holder interface used to avoid generics. /// </summary> internal interface IComputeTaskHolder { /// <summary> /// Perform map step. /// </summary> /// <param name="inStream">Stream with IN data (topology info).</param> /// <param name="outStream">Stream for OUT data (map result).</param> /// <returns>Map with produced jobs.</returns> void Map(PlatformMemoryStream inStream, PlatformMemoryStream outStream); /// <summary> /// Process local job result. /// </summary> /// <param name="jobId">Job pointer.</param> /// <returns>Policy.</returns> int JobResultLocal(ComputeJobHolder jobId); /// <summary> /// Process remote job result. /// </summary> /// <param name="jobId">Job pointer.</param> /// <param name="stream">Stream.</param> /// <returns>Policy.</returns> int JobResultRemote(ComputeJobHolder jobId, PlatformMemoryStream stream); /// <summary> /// Perform task reduce. /// </summary> void Reduce(); /// <summary> /// Complete task. /// </summary> /// <param name="taskHandle">Task handle.</param> void Complete(long taskHandle); /// <summary> /// Complete task with error. /// </summary> /// <param name="taskHandle">Task handle.</param> /// <param name="stream">Stream with serialized exception.</param> void CompleteWithError(long taskHandle, PlatformMemoryStream stream); } /// <summary> /// Compute task holder. /// </summary> internal class ComputeTaskHolder<TA, T, TR> : IComputeTaskHolder { /** Empty results. */ private static readonly IList<IComputeJobResult<T>> EmptyRes = new ReadOnlyCollection<IComputeJobResult<T>>(new List<IComputeJobResult<T>>()); /** Compute instance. */ private readonly ComputeImpl _compute; /** Actual task. */ private readonly IComputeTask<TA, T, TR> _task; /** Task argument. */ private readonly TA _arg; /** Results cache flag. */ private readonly bool _resCache; /** Task future. */ private readonly Future<TR> _fut = new Future<TR>(); /** Jobs whose results are cached. */ private ISet<object> _resJobs; /** Cached results. */ private IList<IComputeJobResult<T>> _ress; /** Handles for jobs which are not serialized right away. */ private volatile List<long> _jobHandles; /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="compute">Compute.</param> /// <param name="task">Task.</param> /// <param name="arg">Argument.</param> public ComputeTaskHolder(Ignite grid, ComputeImpl compute, IComputeTask<TA, T, TR> task, TA arg) { _compute = compute; _arg = arg; _task = task; ResourceTypeDescriptor resDesc = ResourceProcessor.Descriptor(task.GetType()); IComputeResourceInjector injector = task as IComputeResourceInjector; if (injector != null) injector.Inject(grid); else resDesc.InjectIgnite(task, grid); _resCache = !resDesc.TaskNoResultCache; } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User code can throw any exception")] public void Map(PlatformMemoryStream inStream, PlatformMemoryStream outStream) { IList<IClusterNode> subgrid; ClusterGroupImpl prj = (ClusterGroupImpl)_compute.ClusterGroup; var ignite = (Ignite) prj.Ignite; // 1. Unmarshal topology info if topology changed. var reader = prj.Marshaller.StartUnmarshal(inStream); if (reader.ReadBoolean()) { long topVer = reader.ReadLong(); List<IClusterNode> nodes = new List<IClusterNode>(reader.ReadInt()); int nodesCnt = reader.ReadInt(); subgrid = new List<IClusterNode>(nodesCnt); for (int i = 0; i < nodesCnt; i++) { IClusterNode node = ignite.GetNode(reader.ReadGuid()); nodes.Add(node); if (reader.ReadBoolean()) subgrid.Add(node); } // Update parent projection to help other task callers avoid this overhead. // Note that there is a chance that topology changed even further and this update fails. // It means that some of subgrid nodes could have left the Grid. This is not critical // for us, because Java will handle it gracefully. prj.UpdateTopology(topVer, nodes); } else { IList<IClusterNode> nodes = prj.NodesNoRefresh(); Debug.Assert(nodes != null, "At least one topology update should have occurred."); subgrid = IgniteUtils.Shuffle(nodes); } // 2. Perform map. IDictionary<IComputeJob<T>, IClusterNode> map; Exception err; try { map = _task.Map(subgrid, _arg); err = null; } catch (Exception e) { map = null; err = e; // Java can receive another exception in case of marshalling failure but it is not important. Finish(default(TR), e); } // 3. Write map result to the output stream. BinaryWriter writer = prj.Marshaller.StartMarshal(outStream); try { if (err == null) { writer.WriteBoolean(true); // Success flag. if (map == null) writer.WriteBoolean(false); // Map produced no result. else { writer.WriteBoolean(true); // Map produced result. _jobHandles = WriteJobs(writer, map); } } else { writer.WriteBoolean(false); // Map failed. // Write error as string because it is not important for Java, we need only to print // a message in the log. writer.WriteString("Map step failed [errType=" + err.GetType().Name + ", errMsg=" + err.Message + ']'); } } catch (Exception e) { // Something went wrong during marshaling. Finish(default(TR), e); outStream.Reset(); writer.WriteBoolean(false); // Map failed. writer.WriteString(e.Message); // Write error message. } finally { prj.Marshaller.FinishMarshal(writer); } } /// <summary> /// Writes job map. /// </summary> /// <param name="writer">Writer.</param> /// <param name="map">Map</param> /// <returns>Job handle list.</returns> private static List<long> WriteJobs(BinaryWriter writer, IDictionary<IComputeJob<T>, IClusterNode> map) { Debug.Assert(writer != null && map != null); writer.WriteInt(map.Count); // Amount of mapped jobs. var jobHandles = new List<long>(map.Count); var ignite = writer.Marshaller.Ignite; try { foreach (KeyValuePair<IComputeJob<T>, IClusterNode> mapEntry in map) { var job = new ComputeJobHolder(ignite, mapEntry.Key.ToNonGeneric()); IClusterNode node = mapEntry.Value; var jobHandle = ignite.HandleRegistry.Allocate(job); jobHandles.Add(jobHandle); writer.WriteLong(jobHandle); if (node.IsLocal) writer.WriteBoolean(false); // Job is not serialized. else { writer.WriteBoolean(true); // Job is serialized. writer.WriteObject(job); } writer.WriteGuid(node.Id); } } catch (Exception) { foreach (var handle in jobHandles) ignite.HandleRegistry.Release(handle); throw; } return jobHandles; } /** <inheritDoc /> */ public int JobResultLocal(ComputeJobHolder job) { return (int)JobResult0(job.JobResult); } /** <inheritDoc /> */ [SuppressMessage("ReSharper", "PossibleInvalidOperationException")] public int JobResultRemote(ComputeJobHolder job, PlatformMemoryStream stream) { // 1. Unmarshal result. BinaryReader reader = _compute.Marshaller.StartUnmarshal(stream); var nodeId = reader.ReadGuid(); Debug.Assert(nodeId.HasValue); bool cancelled = reader.ReadBoolean(); try { object err; var data = BinaryUtils.ReadInvocationResult(reader, out err); // 2. Process the result. return (int) JobResult0(new ComputeJobResultImpl(data, (Exception) err, job.Job, nodeId.Value, cancelled)); } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to process job result: " + e.Message, e); throw; } } /** <inheritDoc /> */ public void Reduce() { try { TR taskRes = _task.Reduce(_resCache ? _ress : EmptyRes); Finish(taskRes, null); } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to reduce task: " + e.Message, e); throw; } } /** <inheritDoc /> */ public void Complete(long taskHandle) { Clean(taskHandle); } /// <summary> /// Complete task with error. /// </summary> /// <param name="taskHandle">Task handle.</param> /// <param name="e">Error.</param> public void CompleteWithError(long taskHandle, Exception e) { Finish(default(TR), e); Clean(taskHandle); } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User object deserialization can throw any exception")] public void CompleteWithError(long taskHandle, PlatformMemoryStream stream) { BinaryReader reader = _compute.Marshaller.StartUnmarshal(stream); Exception err; try { err = reader.ReadBoolean() ? reader.ReadObject<BinaryObject>().Deserialize<Exception>() : ExceptionUtils.GetException(reader.ReadString(), reader.ReadString()); } catch (Exception e) { err = new IgniteException("Task completed with error, but it cannot be unmarshalled: " + e.Message, e); } CompleteWithError(taskHandle, err); } /// <summary> /// Task completion future. /// </summary> internal Future<TR> Future { get { return _fut; } } /// <summary> /// Manually set job handles. Used by closures because they have separate flow for map step. /// </summary> /// <param name="jobHandles">Job handles.</param> internal void JobHandles(List<long> jobHandles) { _jobHandles = jobHandles; } /// <summary> /// Process job result. /// </summary> /// <param name="res">Result.</param> private ComputeJobResultPolicy JobResult0(IComputeJobResult<object> res) { try { IList<IComputeJobResult<T>> ress0; // 1. Prepare old results. if (_resCache) { if (_resJobs == null) { _resJobs = new HashSet<object>(); _ress = new List<IComputeJobResult<T>>(); } ress0 = _ress; } else ress0 = EmptyRes; // 2. Invoke user code. var policy = _task.OnResult(new ComputeJobResultGenericWrapper<T>(res), ress0); // 3. Add result to the list only in case of success. if (_resCache) { var job = res.Job.Unwrap(); if (!_resJobs.Add(job)) { // Duplicate result => find and replace it with the new one. var oldRes = _ress.Single(item => item.Job == job); _ress.Remove(oldRes); } _ress.Add(new ComputeJobResultGenericWrapper<T>(res)); } return policy; } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to process job result: " + e.Message, e); throw; } } /// <summary> /// Finish task. /// </summary> /// <param name="res">Result.</param> /// <param name="err">Error.</param> private void Finish(TR res, Exception err) { _fut.OnDone(res, err); } /// <summary> /// Clean-up task resources. /// </summary> /// <param name="taskHandle"></param> private void Clean(long taskHandle) { var handles = _jobHandles; var handleRegistry = _compute.Marshaller.Ignite.HandleRegistry; if (handles != null) foreach (var handle in handles) handleRegistry.Release(handle, true); handleRegistry.Release(taskHandle, true); } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using Encog.Util; namespace Encog.App.Quant.Util { /// <summary> /// A buffer of bar segments. /// </summary> public class BarBuffer { /// <summary> /// The bar data loaded. /// </summary> private readonly IList<double[]> data; /// <summary> /// The number of periods. /// </summary> private readonly int periods; /// <summary> /// Construct the object. /// </summary> /// <param name="thePeriods">The number of periods.</param> public BarBuffer(int thePeriods) { data = new List<double[]>(); periods = thePeriods; } /// <value>The data.</value> public IList<double[]> Data { get { return data; } } /// <summary> /// Determine if the buffer is full. /// </summary> /// <value>True if the buffer is full.</value> public bool Full { get { return data.Count >= periods; } } /// <summary> /// Add a bar. /// </summary> /// <param name="d">The bar data.</param> public void Add(double d) { var da = new double[1]; da[0] = d; Add(da); } /// <summary> /// Add a bar. /// </summary> /// <param name="d">The bar data.</param> public void Add(double[] d) { data.Insert(0, EngineArray.ArrayCopy(d)); if (data.Count > periods) { data.RemoveAt(data.Count - 1); } } /// <summary> /// Average all of the bars. /// </summary> /// <param name="idx">The bar index to average.</param> /// <returns>The average.</returns> public double Average(int idx) { double total = 0; for (int i = 0; i < data.Count; i++) { double[] d = data[i]; total += d[idx]; } return total/data.Count; } /// <summary> /// Get the average gain. /// </summary> /// <param name="idx">The field to get the average gain for.</param> /// <returns>The average gain.</returns> public double AverageGain(int idx) { double total = 0; int count = 0; for (int i = 0; i < data.Count - 1; i++) { double[] today = data[i]; double[] yesterday = data[i + 1]; double diff = today[idx] - yesterday[idx]; if (diff > 0) { total += diff; } count++; } if (count == 0) { return 0; } else { return total/count; } } /// <summary> /// Get the average loss. /// </summary> /// <param name="idx">The index to check for.</param> /// <returns>The average loss.</returns> public double AverageLoss(int idx) { double total = 0; int count = 0; for (int i = 0; i < data.Count - 1; i++) { double[] today = data[i]; double[] yesterday = data[i + 1]; double diff = today[idx] - yesterday[idx]; if (diff < 0) { total += Math.Abs(diff); } count++; } if (count == 0) { return 0; } else { return total/count; } } /// <summary> /// Get the max for the specified index. /// </summary> /// <param name="idx">The index to check.</param> /// <returns>The max.</returns> public double Max(int idx) { double result = Double.MinValue; foreach (var d in data) { result = Math.Max(d[idx], result); } return result; } /// <summary> /// Get the min for the specified index. /// </summary> /// <param name="idx">The index to check.</param> /// <returns>The min.</returns> public double Min(int idx) { double result = Double.MaxValue; foreach (var d in data) { result = Math.Min(d[idx], result); } return result; } /// <summary> /// Pop (and remove) the oldest bar in the buffer. /// </summary> /// <returns>The oldest bar in the buffer.</returns> public double[] Pop() { if (data.Count == 0) { return null; } int idx = data.Count - 1; double[] result = data[idx]; data.RemoveAt(idx); return result; } } }
/* Copyright (c) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Diagnostics; namespace Microsoft.Research.DryadLinq { internal class DryadLinqMultiReaderStream : Stream { private DryadLinqBinaryReader[] m_readerArray; private DryadLinqBinaryReader m_curReader; private Int32 m_nextStreamIdx; public DryadLinqMultiReaderStream(DryadLinqBinaryReader[] streamArray) { this.m_readerArray = streamArray; this.m_curReader = streamArray[0]; this.m_nextStreamIdx = 1; } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override bool CanSeek { get { return false; } } public override long Length { get { long len = 0; for (int i = 0; i < this.m_readerArray.Length; i++) { len += this.m_readerArray[i].GetTotalLength(); } return len; } } public override long Position { get { throw new DryadLinqException(DryadLinqErrorCode.PositionNotSupported, SR.PositionNotSupported); } set { throw new DryadLinqException(DryadLinqErrorCode.PositionNotSupported, SR.PositionNotSupported); } } protected override void Dispose(bool disposing) { try { foreach (DryadLinqBinaryReader s in this.m_readerArray) { s.Close(); } } finally { base.Dispose(disposing); } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { while (true) { int n = this.m_curReader.ReadBytes(buffer, offset, count); if (n != 0) return n; if (this.m_nextStreamIdx == this.m_readerArray.Length) return 0; this.m_curReader = this.m_readerArray[this.m_nextStreamIdx++]; } } public override int ReadByte() { while (true) { int b = this.m_curReader.ReadUByte(); if (b != -1) return b; if (this.m_nextStreamIdx == this.m_readerArray.Length) return -1; this.m_curReader = this.m_readerArray[this.m_nextStreamIdx++]; } } public override long Seek(long offset, SeekOrigin origin) { throw new DryadLinqException(DryadLinqErrorCode.SeekNotSupported, SR.SeekNotSupported); } public override void SetLength(long value) { throw new DryadLinqException(DryadLinqErrorCode.SetLengthNotSupported, SR.SetLengthNotSupported); } public override void Write(byte[] buffer, int offset, int count) { throw new DryadLinqException(DryadLinqErrorCode.WriteNotSupported, SR.WriteNotSupported); } public override void WriteByte(byte value) { throw new DryadLinqException(DryadLinqErrorCode.WriteByteNotSupported, SR.WriteByteNotSupported); } } internal class DryadLinqMultiFileStream : Stream { private const int DefaultBuffSize = 8192 * 128; private string[] m_filePathArray; private CompressionScheme m_compressionScheme; private Stream m_curStream; private int m_nextIndex; internal DryadLinqMultiFileStream(string[] filePathArray, CompressionScheme scheme) { this.m_filePathArray = filePathArray; this.m_compressionScheme = scheme; this.m_nextIndex = 0; this.InitNextStream(); } private void InitNextStream() { this.m_curStream = null; if (this.m_nextIndex < this.m_filePathArray.Length) { FileOptions options = FileOptions.SequentialScan; this.m_curStream = new FileStream(this.m_filePathArray[this.m_nextIndex], FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBuffSize, options); if (this.m_compressionScheme != CompressionScheme.None) { if (this.m_compressionScheme == CompressionScheme.Gzip) { this.m_curStream = new GZipStream(this.m_curStream, CompressionMode.Decompress); } else { throw new DryadLinqException(DryadLinqErrorCode.UnknownCompressionScheme, SR.UnknownCompressionScheme); } } this.m_nextIndex++; } } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override bool CanSeek { get { return false; } } public override long Length { get { long len = 0; for (int i = 0; i < this.m_filePathArray.Length; i++) { len += new FileInfo(this.m_filePathArray[i]).Length; } return len; } } public override long Position { get { throw new DryadLinqException(DryadLinqErrorCode.PositionNotSupported, SR.PositionNotSupported); } set { throw new DryadLinqException(DryadLinqErrorCode.PositionNotSupported, SR.PositionNotSupported); } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { while (true) { int n = this.m_curStream.Read(buffer, offset, count); if (n != 0) return n; this.InitNextStream(); if (this.m_curStream == null) return 0; } } public override int ReadByte() { while (true) { int b = this.m_curStream.ReadByte(); if (b != -1) return b; this.InitNextStream(); if (this.m_curStream == null) return 0; } } public override long Seek(long offset, SeekOrigin origin) { throw new DryadLinqException(DryadLinqErrorCode.SeekNotSupported, SR.SeekNotSupported); } public override void SetLength(long value) { throw new DryadLinqException(DryadLinqErrorCode.SetLengthNotSupported, SR.SetLengthNotSupported); } public override void Write(byte[] buffer, int offset, int count) { throw new DryadLinqException(DryadLinqErrorCode.WriteNotSupported, SR.WriteNotSupported); } public override void WriteByte(byte value) { throw new DryadLinqException(DryadLinqErrorCode.WriteByteNotSupported, SR.WriteByteNotSupported); } } }
#pragma warning disable using System.Collections.Generic; using XPT.Games.Generic.Entities; using XPT.Games.Generic.Maps; using XPT.Games.Yserbius; using XPT.Games.Yserbius.Entities; namespace XPT.Games.Yserbius.Maps { class YserMap25 : YsMap { public override int MapIndex => 25; protected override int RandomEncounterChance => 15; protected override int RandomEncounterExtraCount => 2; public YserMap25() { MapEvent01 = FnCHESLITE_01; MapEvent02 = FnCHESDARK_02; MapEvent03 = FnVOID_03; MapEvent04 = FnPOKERBRG_04; MapEvent05 = FnPOKERSW_05; MapEvent06 = FnHEARTSDR_06; MapEvent07 = FnMOONSW_07; MapEvent08 = FnBLAKJAK_08; MapEvent09 = FnBLAKJAKK_09; MapEvent0A = FnCRIB_0A; MapEvent0B = FnCRIBJACK_0B; MapEvent0C = FnCRIBFIVE_0C; MapEvent0D = FnBRDGFALL_0D; MapEvent0E = FnDICEPASS_0E; MapEvent0F = FnDICESNAK_0F; MapEvent10 = FnDICEBOXC_10; MapEvent11 = FnDICEENCA_11; MapEvent12 = FnDICEENCB_12; MapEvent13 = FnBLJKFOUN_13; MapEvent14 = FnCRIBFOUN_14; MapEvent15 = FnDICETRSA_15; MapEvent16 = FnDICETRSB_16; MapEvent17 = FnDICETRSC_17; MapEvent18 = FnDICETRSD_18; MapEvent19 = FnDICETRSE_19; MapEvent1A = FnDICETRSF_1A; MapEvent1B = FnDICETRSG_1B; MapEvent1C = FnDICETRSH_1C; MapEvent1D = FnDICETRSI_1D; MapEvent22 = FnBARD_22; MapEvent23 = FnAPPLES_23; MapEvent24 = FnAPPLEENC_24; MapEvent25 = FnCHESENCA_25; MapEvent26 = FnCHESENCB_26; MapEvent27 = FnCHESENCC_27; MapEvent28 = FnCHESENCD_28; MapEvent29 = FnCHESENCE_29; MapEvent2A = FnCHESENCF_2A; MapEvent2B = FnPOKRENCA_2B; MapEvent2C = FnCRIBENCA_2C; MapEvent2D = FnBLJKENCA_2D; MapEvent2E = FnBLJKENCB_2E; MapEvent2F = FnCRIBENCB_2F; MapEvent30 = FnVARYENCA_30; MapEvent31 = FnVARYENCB_31; MapEvent34 = FnVARYENCE_34; MapEvent35 = FnGATEA_35; MapEvent36 = FnTOLABY_36; MapEvent37 = FnTXTCHESL_37; MapEvent38 = FnTXTCHESD_38; MapEvent39 = FnTXTDICEB_39; MapEvent3A = FnTXTDICEA_3A; } // === Strings ================================================ private const string String03FC = "You may leave the chessboard through this opening."; private const string String042F = "A knight move here would place you off the chessboard!"; private const string String0466 = "With a chess piece you may step across the chessboard."; private const string String049D = "You may leave the chessboard through this opening."; private const string String04D0 = "A knight move here would place you off the chessboard!"; private const string String0507 = "With a chess piece you may step across the chessboard."; private const string String053E = "You fall to your death in the lava below!"; private const string String0568 = "Planks of the Poker Bridge are made from used playing cards."; private const string String05A5 = "The rickety bridge barely holds your weight."; private const string String05D2 = "The bridge collapses as you step on it, sending you to your death."; private const string String0615 = "The King laughs at his clever ruse."; private const string String0639 = "The royal flush beats the Joker! A bridge forms across the pit."; private const string String067A = "A bottomless pit lies before you, and a broken bridge spans the pit."; private const string String06BF = "Upon each board are the symbols for 10, Jack, Queen and Ace. A voice proclaims, 'I call your bluff'."; private const string String0725 = "The door bellows, 'I am all hearts!'"; private const string String074A = "The door proclaims, 'You shot the Moon!'"; private const string String0774 = "A small button, shaped like the crescent moon, lies just out of reach."; private const string String07BB = "The Ace is played as eleven points, scoring the BlackJack!"; private const string String07F6 = "A door unlocks..."; private const string String0808 = "You enter a treasure room without any treasure."; private const string String0838 = "A dwarf thief voice menacingly orders, 'The Kings guard their treasure. Only one can find it.'"; private const string String0898 = "Stand back! A King guards this wall!"; private const string String08BE = "The Jack scores the hand 22. Cribbage is the game."; private const string String08F2 = "A door unlocks..."; private const string String0904 = "The 22nd room of this fine castle..."; private const string String0929 = "On the floor is a five, on two walls are fives, and the third wall holds a Jack."; private const string String097A = "A voice laughs, 'You stand on face up!'"; private const string String09A2 = "I, the Jack, throw dust in your general direction."; private const string String09D5 = "The 5 card smiles back."; private const string String09ED = "The Poker Bridge behind you collapses."; private const string String0A14 = "Lucky Sevens! Lucky Sevens on the first roll!"; private const string String0A42 = "The door says, 'Snake eyes' ..."; private const string String0A62 = "The door shows two squares of six. 'Box Cars' ..."; private const string String0A95 = "The Blackjack Fountain is made of playing cards."; private const string String0AC6 = "Still water fills the basin."; private const string String0AE3 = "A sip of it makes you feel healthier and more agile."; private const string String0B18 = "As you sip, a voice whispers -"; private const string String0B37 = "'The Jack has come home. Thank you for your help.'"; private const string String0B6B = "The fountain is dry as a bone."; private const string String0B8A = "The Cribbage Fountain is bedecked with golden pegs."; private const string String0BBE = "A puff of steam from the fountain blows in your face."; private const string String0BF4 = "Your Mana is restored and you feel readier to fight."; private const string String0C29 = "A voice whispers -"; private const string String0C3C = "'The Ace has returned. Three points for you.'"; private const string String0C6B = "The basin is empty."; private const string String0C7F = "A message is inscribed on a wall -- "; private const string String0CA4 = "'The Waters of Winter are needed to transform Spring into Summer."; private const string String0CE6 = "In return for your deeds, you will receive the Radiance of Summer.'"; private const string String0D2A = "A note is inscribed on a wall -- "; private const string String0D4C = "'To reach En-Li-Kil, you must defeat his Wind Elemental."; private const string String0D85 = "Remember to use weapons that do not break when the Wind Elemental attacks."; private const string String0DD0 = "A message is written in blood on a wall -- "; private const string String0DFC = "'Be careful in the River of Eternity."; private const string String0E22 = "The river takes one fourth of your full health every step you take with no opportunity to heal."; private const string String0E82 = "'A safe fourth square must be found to cross the Rivers of Eternity.'"; private const string String0EC8 = "A message is written on a wall -- "; private const string String0EEB = "'Use the outer walls to set the location of another's next step in the Parapet Chasm."; private const string String0F41 = "Once across, encounter Andreas to gain access to Arnakkian.'"; private const string String0F7E = "A message is written on a wall -- "; private const string String0FA1 = "'The Promise of Spring Renewal must be sworn to convert Autumn to Winter."; private const string String0FEB = "In return you will receive the cold Waters of Winter.'"; private const string String1022 = "An Elf Ranger appears."; private const string String1039 = "'In levels below the labyrinth, Snow Elves hide from the curses "; private const string String107A = "of Arnakkian and await the day they may return to their faraway land."; private const string String10C0 = "A proud tree may be found in their caves."; private const string String10EA = "The Snow Elves call this grand tree the Aldbora."; private const string String111B = "The Aldbora bears the fruit of knowledge to all adventurers during the season of winter."; private const string String1174 = "It lies dormant now, unable to ripen its fruit without the change of seasons and the Radiance of Summer.'"; private const string String11DE = "A message is scrawled on a wall -- "; private const string String1202 = "'Use the Autumn Seeds to transform Winter into flowering Spring."; private const string String1243 = "The promise of Spring Renewal for another year will be given in return.'"; private const string String128C = "A message is carved in the floor -- "; private const string String12B1 = "'The bones of a past king may be found in the Elven Caves.'"; private const string String12ED = "A message is scribbled on a wall -- "; private const string String1312 = "'The trumpet sound of the Harvest Horn will announce Summer's conversion to Autumn."; private const string String1366 = "From the conversion you will receive the seeds of Autumn.'"; private const string String13A1 = "A ghost elf bard sings a tale of how four colored magical gems placed side by side can form a rainbow to a far away island."; private const string String141D = "The spirit of a beautiful wench appears. She hold a wooden bucket filled wtih floating apples."; private const string String147C = "'Step forward and honor me with your kindness! Bob for apples and win a prize.'"; private const string String14CD = "You have accepted the ghost's challenge."; private const string String14F6 = "You close your eyes and dunk your head into the wood bucket."; private const string String1533 = "The ripe apples are rotten and filled with Leeches!"; private const string String1567 = "You are able to dodge several bursts of flame as you enter a Dragon's Lair."; private const string String15B3 = "The gate takes you back to the labyrinth."; private const string String15DD = "Use the red squares and you shall turn clockwise on your mount."; private const string String161D = "The stallion must go counterclockwise on blue squares!"; private const string String1654 = "To the west you will find a second dice maze."; private const string String1682 = "A maze made out of dice lies just to the north."; // === Functions ================================================ private void FnCHESLITE_01(YsPlayerServer player, MapEventType type, bool doMsgs) { if (GetCurrentTile(player) == 0x0062 && GetFacing(player) == 0) { ShowMessage(player, doMsgs, String03FC); // You may leave the chessboard through this opening. return; } if (GetCurrentTile(player) == 0x0069 && GetFacing(player) == 2) { ShowMessage(player, doMsgs, String03FC); // You may leave the chessboard through this opening. return; } if (GetCurrentTile(player) == 0x0092 && GetFacing(player) == 0) { ShowMessage(player, doMsgs, String03FC); // You may leave the chessboard through this opening. return; } if (GetCurrentTile(player) == 0x0099 && GetFacing(player) == 2) { ShowMessage(player, doMsgs, String03FC); // You may leave the chessboard through this opening. return; } SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00); if (HasItem(player, YsIndexes.ItemChessPiece) == 0) { ShowMessage(player, doMsgs, String0466); // With a chess piece you may step across the chessboard. return; } ushort nextTile = (ushort)GetCurrentTile(player); switch (GetFacing(player)) { case 0: // west nextTile += 0xFFEE; break; case 1: // south nextTile += 0x001F; // break; case 2: // east nextTile += 0x0012; // break; case 3: // north nextTile += 0xFFE1; // break; } int x = nextTile & 0x000f; int y = nextTile & 0x00f0; if (x < 2 || x > 9 || y < 0x40 || y > 0xB0) { ShowMessage(player, doMsgs, String042F); // A knight move here would place you off the chessboard! return; } TeleportParty(player, 0x35, 0x02, nextTile, GetFacing(player), type); } private void FnCHESDARK_02(YsPlayerServer player, MapEventType type, bool doMsgs) { if (GetCurrentTile(player) == 0x0062 && GetFacing(player) == 0) { ShowMessage(player, doMsgs, String03FC); // You may leave the chessboard through this opening. return; } if (GetCurrentTile(player) == 0x0069 && GetFacing(player) == 2) { ShowMessage(player, doMsgs, String03FC); // You may leave the chessboard through this opening. return; } if (GetCurrentTile(player) == 0x0092 && GetFacing(player) == 0) { ShowMessage(player, doMsgs, String03FC); // You may leave the chessboard through this opening. return; } if (GetCurrentTile(player) == 0x0099 && GetFacing(player) == 2) { ShowMessage(player, doMsgs, String03FC); // You may leave the chessboard through this opening. return; } SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00); if (HasItem(player, YsIndexes.ItemChessPiece) == 0) { ShowMessage(player, doMsgs, String0466); // With a chess piece you may step across the chessboard. return; } ushort nextTile = (ushort)GetCurrentTile(player); switch (GetFacing(player)) { case 0: // west nextTile += 0x000E; break; case 1: // south nextTile += 0x0021; // break; case 2: // east nextTile += 0xFFF2; // -y, +x break; case 3: // north nextTile += 0xFFDF; // break; } int x = nextTile & 0x000f; int y = nextTile & 0x00f0; if (x < 2 || x > 9 || y < 0x40 || y > 0xB0) { ShowMessage(player, doMsgs, String042F); // A knight move here would place you off the chessboard! return; } TeleportParty(player, 0x35, 0x02, nextTile, GetFacing(player), type); } private void FnVOID_03(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String053E); // You fall to your death in the lava below! DamagePlayer(player, GetMaxHits(player)); } private void FnPOKERBRG_04(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0568); // Planks of the Poker Bridge are made from used playing cards. Compare(GetFlag(player, FlagTypeMap, 0x01), 0x0001); if (JumpNotEqual) { ShowMessage(player, doMsgs, String05D2); // The bridge collapses as you step on it, sending you to your death. ShowMessage(player, doMsgs, String0615); // The King laughs at his clever ruse. DamagePlayer(player, GetMaxHits(player)); return; } ShowMessage(player, doMsgs, String05A5); // The rickety bridge barely holds your weight. SetFloorItem(player, 0x00, 0xDD); SetFloorPassable(player, 0xDD, 0x01); } private void FnPOKERSW_05(YsPlayerServer player, MapEventType type, bool doMsgs) { if (HasUsedItem(player, type, ref doMsgs, YsIndexes.ItemKingOfSpades, YsIndexes.ItemKingOfSpades) == 0) { ShowMessage(player, doMsgs, String067A); // A bottomless pit lies before you, and a broken bridge spans the pit. ShowMessage(player, doMsgs, String06BF); // Upon each board are the symbols for 10, Jack, Queen and Ace. A voice proclaims, 'I call your bluff'. return; } SetFlag(player, FlagTypeMap, 0x01, 0x01); SetFloorItem(player, 0x00, 0xDD); SetFloorPassable(player, 0xDD, 0x01); ShowMessage(player, doMsgs, String0639); // The royal flush beats the Joker! A bridge forms across the pit. } private void FnHEARTSDR_06(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0725); // The door bellows, 'I am all hearts!' } private void FnMOONSW_07(YsPlayerServer player, MapEventType type, bool doMsgs) { if (HasUsedItem(player, type, ref doMsgs, YsIndexes.ItemQueenOfSpades, YsIndexes.ItemQueenOfSpades) == 0) { ShowMessage(player, doMsgs, String0774); // A small button, shaped like the crescent moon, lies just out of reach. return; } SetWallItem(player, 0x01, 0xBF, 0x03); SetWallPassable(player, 0xBF, 0x03, 0x01); ShowMessage(player, doMsgs, String074A); // The door proclaims, 'You shot the Moon!' } private void FnBLAKJAK_08(YsPlayerServer player, MapEventType type, bool doMsgs) { if (HasUsedItem(player, type, ref doMsgs, YsIndexes.ItemAceOfSpades, YsIndexes.ItemAceOfSpades) == 0) goto L0060; SetWallItem(player, 0x01, 0x8D, 0x01); SetWallPassable(player, 0x8D, 0x01, 0x01); ShowMessage(player, doMsgs, String07BB); // The Ace is played as eleven points, scoring the BlackJack! ShowMessage(player, doMsgs, String07F6); // A door unlocks... return; L0060: ShowMessage(player, doMsgs, String0808); // You enter a treasure room without any treasure. ShowMessage(player, doMsgs, String0838); // A dwarf thief voice menacingly orders, 'The Kings guard their treasure. Only one can find it.' } private void FnBLAKJAKK_09(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0898); // Stand back! A King guards this wall! } private void FnCRIB_0A(YsPlayerServer player, MapEventType type, bool doMsgs) { if (HasUsedItem(player, type, ref doMsgs, YsIndexes.ItemJackOfSpades, YsIndexes.ItemJackOfSpades) == 0) goto L0060; SetWallItem(player, 0x01, 0x7D, 0x03); SetWallPassable(player, 0x7D, 0x03, 0x01); ShowMessage(player, doMsgs, String08BE); // The Jack scores the hand 22. Cribbage is the game. ShowMessage(player, doMsgs, String08F2); // A door unlocks... return; L0060: ShowMessage(player, doMsgs, String0904); // The 22nd room of this fine castle... ShowMessage(player, doMsgs, String0929); // On the floor is a five, on two walls are fives, and the third wall holds a Jack. ShowMessage(player, doMsgs, String097A); // A voice laughs, 'You stand on face up!' } private void FnCRIBJACK_0B(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String09A2); // I, the Jack, throw dust in your general direction. } private void FnCRIBFIVE_0C(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String09D5); // The 5 card smiles back. } private void FnBRDGFALL_0D(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String09ED); // The Poker Bridge behind you collapses. SetFlag(player, FlagTypeMap, 0x01, 0x00); SetFloorItem(player, 0x01, 0xDD); } private void FnDICEPASS_0E(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0A14); // Lucky Sevens! Lucky Sevens on the first roll! } private void FnDICESNAK_0F(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0A42); // The door says, 'Snake eyes' ... } private void FnDICEBOXC_10(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0A62); // The door shows two squares of six. 'Box Cars' ... } private void FnDICEENCA_11(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x0A); AddEncounter(player, 0x02, 0x0A); AddEncounter(player, 0x03, 0x0A); AddEncounter(player, 0x04, 0x0A); AddEncounter(player, 0x05, 0x04); AddEncounter(player, 0x06, 0x04); } private void FnDICEENCB_12(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x0A); AddEncounter(player, 0x02, 0x0A); AddEncounter(player, 0x03, 0x0A); AddEncounter(player, 0x04, 0x0A); AddEncounter(player, 0x05, 0x0A); AddEncounter(player, 0x06, 0x0A); } private void FnBLJKFOUN_13(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0A95); // The Blackjack Fountain is made of playing cards. RefreshCompareFlags(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagModAttr_BlackjackFountain)); if (JumpEqual) goto L0028; goto L00AF; L0028: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagModAttr_BlackjackFountain, 0x01); RemoveItem(player, YsIndexes.ItemJackOfSpades); ShowPortrait(player, 0x0042); ModifyAttribute(player, 0x02, 0x0003); HealPlayer(player, (ushort)GetMaxHits(player)); ShowMessage(player, doMsgs, String0AC6); // Still water fills the basin. ShowMessage(player, doMsgs, String0AE3); // A sip of it makes you feel healthier and more agile. ShowMessage(player, doMsgs, String0B18); // As you sip, a voice whispers - ShowMessage(player, doMsgs, String0B37); // 'The Jack has come home. Thank you for your help.' return; L00AF: ShowMessage(player, doMsgs, String0B6B); // The fountain is dry as a bone. } private void FnCRIBFOUN_14(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0B8A); // The Cribbage Fountain is bedecked with golden pegs. RefreshCompareFlags(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagModAttr_CribbageFountain)); if (JumpEqual) goto L0028; goto L00AB; L0028: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagModAttr_CribbageFountain, 0x01); ShowPortrait(player, 0x0042); RemoveItem(player, YsIndexes.ItemAceOfSpades); ModifyAttribute(player, 0x03, 0x0003); AddMana(player, 0x0BB8); ShowMessage(player, doMsgs, String0BBE); // A puff of steam from the fountain blows in your face. ShowMessage(player, doMsgs, String0BF4); // Your Mana is restored and you feel readier to fight. ShowMessage(player, doMsgs, String0C29); // A voice whispers - ShowMessage(player, doMsgs, String0C3C); // 'The Ace has returned. Three points for you.' return; L00AB: ShowMessage(player, doMsgs, String0C6B); // The basin is empty. } private void FnDICETRSA_15(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0C7F); // A message is inscribed on a wall -- ShowRunes(player, doMsgs, String0CA4); // 'The Waters of Winter are needed to transform Spring into Summer. ShowRunes(player, doMsgs, String0CE6); // In return for your deeds, you will receive the Radiance of Summer.' } private void FnDICETRSB_16(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0D2A); // A note is inscribed on a wall -- ShowRunes(player, doMsgs, String0D4C); // 'To reach En-Li-Kil, you must defeat his Wind Elemental. ShowRunes(player, doMsgs, String0D85); // Remember to use weapons that do not break when the Wind Elemental attacks. } private void FnDICETRSC_17(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0DD0); // A message is written in blood on a wall -- ShowRunes(player, doMsgs, String0DFC); // 'Be careful in the River of Eternity. ShowRunes(player, doMsgs, String0E22); // The river takes one fourth of your full health every step you take with no opportunity to heal. ShowRunes(player, doMsgs, String0E82); // 'A safe fourth square must be found to cross the Rivers of Eternity.' } private void FnDICETRSD_18(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0EC8); // A message is written on a wall -- ShowRunes(player, doMsgs, String0EEB); // 'Use the outer walls to set the location of another's next step in the Parapet Chasm. ShowRunes(player, doMsgs, String0F41); // Once across, encounter Andreas to gain access to Arnakkian.' } private void FnDICETRSE_19(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0F7E); // A message is written on a wall -- ShowRunes(player, doMsgs, String0FA1); // 'The Promise of Spring Renewal must be sworn to convert Autumn to Winter. ShowRunes(player, doMsgs, String0FEB); // In return you will receive the cold Waters of Winter.' } private void FnDICETRSF_1A(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, 0x001F); ShowMessage(player, doMsgs, String1022); // An Elf Ranger appears. ShowMessage(player, doMsgs, String1039); // 'In levels below the labyrinth, Snow Elves hide from the curses ShowMessage(player, doMsgs, String107A); // of Arnakkian and await the day they may return to their faraway land. ShowMessage(player, doMsgs, String10C0); // A proud tree may be found in their caves. ShowMessage(player, doMsgs, String10EA); // The Snow Elves call this grand tree the Aldbora. ShowMessage(player, doMsgs, String111B); // The Aldbora bears the fruit of knowledge to all adventurers during the season of winter. ShowMessage(player, doMsgs, String1174); // It lies dormant now, unable to ripen its fruit without the change of seasons and the Radiance of Summer.' } private void FnDICETRSG_1B(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String11DE); // A message is scrawled on a wall -- ShowRunes(player, doMsgs, String1202); // 'Use the Autumn Seeds to transform Winter into flowering Spring. ShowRunes(player, doMsgs, String1243); // The promise of Spring Renewal for another year will be given in return.' } private void FnDICETRSH_1C(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String128C); // A message is carved in the floor -- ShowRunes(player, doMsgs, String12B1); // 'The bones of a past king may be found in the Elven Caves.' } private void FnDICETRSI_1D(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String12ED); // A message is scribbled on a wall -- ShowRunes(player, doMsgs, String1312); // 'The trumpet sound of the Harvest Horn will announce Summer's conversion to Autumn. ShowRunes(player, doMsgs, String1366); // From the conversion you will receive the seeds of Autumn.' } private void FnBARD_22(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String13A1); // A ghost elf bard sings a tale of how four colored magical gems placed side by side can form a rainbow to a far away island. } private void FnAPPLES_23(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String141D); // The spirit of a beautiful wench appears. She hold a wooden bucket filled wtih floating apples. ShowMessage(player, doMsgs, String147C); // 'Step forward and honor me with your kindness! Bob for apples and win a prize.' } private void FnAPPLEENC_24(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String14CD); // You have accepted the ghost's challenge. ShowMessage(player, doMsgs, String14F6); // You close your eyes and dunk your head into the wood bucket. ShowMessage(player, doMsgs, String1533); // The ripe apples are rotten and filled with Leeches! AddEncounter(player, 0x01, 0x1A); AddEncounter(player, 0x02, 0x1A); AddEncounter(player, 0x03, 0x1B); AddEncounter(player, 0x04, 0x1B); AddEncounter(player, 0x05, 0x1A); AddEncounter(player, 0x06, 0x1A); } private void FnCHESENCA_25(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x1C); AddEncounter(player, 0x02, 0x1D); AddEncounter(player, 0x03, 0x1E); AddEncounter(player, 0x04, 0x1F); AddEncounter(player, 0x05, 0x20); AddEncounter(player, 0x06, 0x21); } private void FnCHESENCB_26(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x1E); AddEncounter(player, 0x02, 0x1E); AddEncounter(player, 0x03, 0x1E); AddEncounter(player, 0x04, 0x1E); AddEncounter(player, 0x05, 0x1E); AddEncounter(player, 0x06, 0x1E); } private void FnCHESENCC_27(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x1F); AddEncounter(player, 0x02, 0x1F); AddEncounter(player, 0x03, 0x1F); AddEncounter(player, 0x04, 0x1F); AddEncounter(player, 0x05, 0x1F); AddEncounter(player, 0x06, 0x1F); } private void FnCHESENCD_28(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x20); AddEncounter(player, 0x02, 0x20); AddEncounter(player, 0x03, 0x20); AddEncounter(player, 0x04, 0x20); AddEncounter(player, 0x05, 0x26); AddEncounter(player, 0x06, 0x26); } private void FnCHESENCE_29(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x22); AddEncounter(player, 0x02, 0x22); AddEncounter(player, 0x03, 0x22); AddEncounter(player, 0x04, 0x22); AddEncounter(player, 0x05, 0x22); AddEncounter(player, 0x06, 0x1D); if (HasItem(player, YsIndexes.ItemQueenOfSpades) == 0) { AddTreasure(player, 0x03E8, 0x00, 0x00, 0x00, YsIndexes.ItemQueenOfSpades, 0xD0); } else { AddTreasure(player, 0x0000, 0x00, 0x00, 0x00, 0x90, 0xAF); } } private void FnCHESENCF_2A(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x18); AddEncounter(player, 0x02, 0x18); AddEncounter(player, 0x03, 0x15); AddEncounter(player, 0x04, 0x18); AddEncounter(player, 0x05, 0x15); AddEncounter(player, 0x06, 0x1C); if (HasItem(player, YsIndexes.ItemKingOfSpades) == 0) { AddTreasure(player, 0x03E8, 0x00, 0x00, 0x00, YsIndexes.ItemKingOfSpades, 0xD0); } else { AddTreasure(player, 0x0000, 0x00, 0x00, 0x00, 0x8D, 0xCF); } } private void FnPOKRENCA_2B(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x1F); AddEncounter(player, 0x02, 0x1F); AddEncounter(player, 0x03, 0x1F); AddEncounter(player, 0x04, 0x1F); AddEncounter(player, 0x05, 0x1F); AddEncounter(player, 0x06, 0x1F); } private void FnCRIBENCA_2C(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x23); AddEncounter(player, 0x02, 0x23); AddEncounter(player, 0x05, 0x23); AddEncounter(player, 0x06, 0x23); AddTreasure(player, 0x2710, 0x00, 0x00, 0xD0, 0xD0, 0x71); } private void FnBLJKENCA_2D(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x26); AddEncounter(player, 0x02, 0x26); AddEncounter(player, 0x03, 0x26); AddEncounter(player, 0x04, 0x26); AddEncounter(player, 0x05, 0x26); AddEncounter(player, 0x06, 0x26); AddTreasure(player, 0x2710, 0x00, 0x00, 0x00, 0xD0, 0x1D); } private void FnBLJKENCB_2E(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x26); AddEncounter(player, 0x02, 0x26); AddEncounter(player, 0x03, 0x26); AddEncounter(player, 0x04, 0x26); AddEncounter(player, 0x05, 0x26); AddEncounter(player, 0x06, 0x26); AddTreasure(player, 0x2710, 0x00, 0x00, 0x00, 0xD0, 0xBE); } private void FnCRIBENCB_2F(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String1567); // You are able to dodge several bursts of flame as you enter a Dragon's Lair. AddEncounter(player, 0x01, 0x24); AddEncounter(player, 0x02, 0x24); AddEncounter(player, 0x03, 0x24); AddEncounter(player, 0x05, 0x25); AddEncounter(player, 0x06, 0x25); AddTreasure(player, 0x2710, 0x00, 0x00, 0xCF, 0xBD, 0x5C); } private void FnVARYENCA_30(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x04); AddEncounter(player, 0x02, 0x04); AddEncounter(player, 0x04, 0x04); AddEncounter(player, 0x05, 0x04); } private void FnVARYENCB_31(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x0E); AddEncounter(player, 0x02, 0x0E); AddEncounter(player, 0x03, 0x0E); AddEncounter(player, 0x05, 0x0D); } private void FnVARYENCE_34(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x13); AddEncounter(player, 0x02, 0x13); AddEncounter(player, 0x03, 0x13); AddEncounter(player, 0x04, 0x13); AddEncounter(player, 0x05, 0x17); AddEncounter(player, 0x06, 0x02); } private void FnGATEA_35(YsPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, 0x35, 0x01, 0x3F, 0x00, type); } private void FnTOLABY_36(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String15B3); // The gate takes you back to the labyrinth. } private void FnTXTCHESL_37(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String15DD); // Use the red squares and you shall turn clockwise on your mount. } private void FnTXTCHESD_38(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String161D); // The stallion must go counterclockwise on blue squares! } private void FnTXTDICEB_39(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String1654); // To the west you will find a second dice maze. } private void FnTXTDICEA_3A(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String1682); // A maze made out of dice lies just to the north. } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="GlobalLB.WideIPBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBWideIPWideIPPool))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBWideIPWideIPRule))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBWideIPWideIPStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonObjectStatus))] public partial class GlobalLBWideIP : iControlInterface { public GlobalLBWideIP() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_alias //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void add_alias( string [] wide_ips, string [] [] aliases ) { this.Invoke("add_alias", new object [] { wide_ips, aliases}); } public System.IAsyncResult Beginadd_alias(string [] wide_ips,string [] [] aliases, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_alias", new object[] { wide_ips, aliases}, callback, asyncState); } public void Endadd_alias(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_metadata //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void add_metadata( string [] wide_ips, string [] [] names, string [] [] values ) { this.Invoke("add_metadata", new object [] { wide_ips, names, values}); } public System.IAsyncResult Beginadd_metadata(string [] wide_ips,string [] [] names,string [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_metadata", new object[] { wide_ips, names, values}, callback, asyncState); } public void Endadd_metadata(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_wideip_pool //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void add_wideip_pool( string [] wide_ips, GlobalLBWideIPWideIPPool [] [] wideip_pools ) { this.Invoke("add_wideip_pool", new object [] { wide_ips, wideip_pools}); } public System.IAsyncResult Beginadd_wideip_pool(string [] wide_ips,GlobalLBWideIPWideIPPool [] [] wideip_pools, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_wideip_pool", new object[] { wide_ips, wideip_pools}, callback, asyncState); } public void Endadd_wideip_pool(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_wideip_rule //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void add_wideip_rule( string [] wide_ips, GlobalLBWideIPWideIPRule [] [] wideip_rules ) { this.Invoke("add_wideip_rule", new object [] { wide_ips, wideip_rules}); } public System.IAsyncResult Beginadd_wideip_rule(string [] wide_ips,GlobalLBWideIPWideIPRule [] [] wideip_rules, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_wideip_rule", new object[] { wide_ips, wideip_rules}, callback, asyncState); } public void Endadd_wideip_rule(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void create( string [] wide_ips, GlobalLBLBMethod [] lb_methods, GlobalLBWideIPWideIPPool [] [] wideip_pools, GlobalLBWideIPWideIPRule [] [] wideip_rules ) { this.Invoke("create", new object [] { wide_ips, lb_methods, wideip_pools, wideip_rules}); } public System.IAsyncResult Begincreate(string [] wide_ips,GlobalLBLBMethod [] lb_methods,GlobalLBWideIPWideIPPool [] [] wideip_pools,GlobalLBWideIPWideIPRule [] [] wideip_rules, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { wide_ips, lb_methods, wideip_pools, wideip_rules}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_wideips //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void delete_all_wideips( ) { this.Invoke("delete_all_wideips", new object [0]); } public System.IAsyncResult Begindelete_all_wideips(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_wideips", new object[0], callback, asyncState); } public void Enddelete_all_wideips(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_wideip //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void delete_wideip( string [] wide_ips ) { this.Invoke("delete_wideip", new object [] { wide_ips}); } public System.IAsyncResult Begindelete_wideip(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_wideip", new object[] { wide_ips}, callback, asyncState); } public void Enddelete_wideip(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_alias //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_alias( string [] wide_ips ) { object [] results = this.Invoke("get_alias", new object [] { wide_ips}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_alias(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_alias", new object[] { wide_ips}, callback, asyncState); } public string [] [] Endget_alias(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBWideIPWideIPStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((GlobalLBWideIPWideIPStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public GlobalLBWideIPWideIPStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBWideIPWideIPStatistics)(results[0])); } //----------------------------------------------------------------------- // get_application //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_application( string [] wide_ips ) { object [] results = this.Invoke("get_application", new object [] { wide_ips}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_application(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_application", new object[] { wide_ips}, callback, asyncState); } public string [] Endget_application(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] wide_ips ) { object [] results = this.Invoke("get_description", new object [] { wide_ips}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { wide_ips}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_enabled_state( string [] wide_ips ) { object [] results = this.Invoke("get_enabled_state", new object [] { wide_ips}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_enabled_state(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_enabled_state", new object[] { wide_ips}, callback, asyncState); } public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_ipv6_no_error_negative_ttl //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_ipv6_no_error_negative_ttl( string [] wide_ips ) { object [] results = this.Invoke("get_ipv6_no_error_negative_ttl", new object [] { wide_ips}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_ipv6_no_error_negative_ttl(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ipv6_no_error_negative_ttl", new object[] { wide_ips}, callback, asyncState); } public long [] Endget_ipv6_no_error_negative_ttl(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_ipv6_no_error_response_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_ipv6_no_error_response_state( string [] wide_ips ) { object [] results = this.Invoke("get_ipv6_no_error_response_state", new object [] { wide_ips}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_ipv6_no_error_response_state(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ipv6_no_error_response_state", new object[] { wide_ips}, callback, asyncState); } public CommonEnabledState [] Endget_ipv6_no_error_response_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_last_resort_pool //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_last_resort_pool( string [] wide_ips ) { object [] results = this.Invoke("get_last_resort_pool", new object [] { wide_ips}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_last_resort_pool(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_last_resort_pool", new object[] { wide_ips}, callback, asyncState); } public string [] Endget_last_resort_pool(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_lb_decision_log_verbosity //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBWideIPLBDecisionLogVerbosity [] [] get_lb_decision_log_verbosity( string [] wide_ips ) { object [] results = this.Invoke("get_lb_decision_log_verbosity", new object [] { wide_ips}); return ((GlobalLBWideIPLBDecisionLogVerbosity [] [])(results[0])); } public System.IAsyncResult Beginget_lb_decision_log_verbosity(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_lb_decision_log_verbosity", new object[] { wide_ips}, callback, asyncState); } public GlobalLBWideIPLBDecisionLogVerbosity [] [] Endget_lb_decision_log_verbosity(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBWideIPLBDecisionLogVerbosity [] [])(results[0])); } //----------------------------------------------------------------------- // get_lb_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBLBMethod [] get_lb_method( string [] wide_ips ) { object [] results = this.Invoke("get_lb_method", new object [] { wide_ips}); return ((GlobalLBLBMethod [])(results[0])); } public System.IAsyncResult Beginget_lb_method(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_lb_method", new object[] { wide_ips}, callback, asyncState); } public GlobalLBLBMethod [] Endget_lb_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBLBMethod [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_metadata //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_metadata( string [] wide_ips ) { object [] results = this.Invoke("get_metadata", new object [] { wide_ips}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_metadata(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_metadata", new object[] { wide_ips}, callback, asyncState); } public string [] [] Endget_metadata(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_metadata_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_metadata_description( string [] wide_ips, string [] [] names ) { object [] results = this.Invoke("get_metadata_description", new object [] { wide_ips, names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_metadata_description(string [] wide_ips,string [] [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_metadata_description", new object[] { wide_ips, names}, callback, asyncState); } public string [] [] Endget_metadata_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_metadata_persistence //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonMetadataPersistence [] [] get_metadata_persistence( string [] wide_ips, string [] [] names ) { object [] results = this.Invoke("get_metadata_persistence", new object [] { wide_ips, names}); return ((CommonMetadataPersistence [] [])(results[0])); } public System.IAsyncResult Beginget_metadata_persistence(string [] wide_ips,string [] [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_metadata_persistence", new object[] { wide_ips, names}, callback, asyncState); } public CommonMetadataPersistence [] [] Endget_metadata_persistence(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonMetadataPersistence [] [])(results[0])); } //----------------------------------------------------------------------- // get_metadata_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_metadata_value( string [] wide_ips, string [] [] names ) { object [] results = this.Invoke("get_metadata_value", new object [] { wide_ips, names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_metadata_value(string [] wide_ips,string [] [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_metadata_value", new object[] { wide_ips, names}, callback, asyncState); } public string [] [] Endget_metadata_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_object_status //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonObjectStatus [] get_object_status( string [] wide_ips ) { object [] results = this.Invoke("get_object_status", new object [] { wide_ips}); return ((CommonObjectStatus [])(results[0])); } public System.IAsyncResult Beginget_object_status(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_object_status", new object[] { wide_ips}, callback, asyncState); } public CommonObjectStatus [] Endget_object_status(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonObjectStatus [])(results[0])); } //----------------------------------------------------------------------- // get_persistence_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_persistence_state( string [] wide_ips ) { object [] results = this.Invoke("get_persistence_state", new object [] { wide_ips}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_persistence_state(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_persistence_state", new object[] { wide_ips}, callback, asyncState); } public CommonEnabledState [] Endget_persistence_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_persistence_ttl //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_persistence_ttl( string [] wide_ips ) { object [] results = this.Invoke("get_persistence_ttl", new object [] { wide_ips}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_persistence_ttl(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_persistence_ttl", new object[] { wide_ips}, callback, asyncState); } public long [] Endget_persistence_ttl(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBWideIPWideIPStatistics get_statistics( string [] wide_ips ) { object [] results = this.Invoke("get_statistics", new object [] { wide_ips}); return ((GlobalLBWideIPWideIPStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { wide_ips}, callback, asyncState); } public GlobalLBWideIPWideIPStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBWideIPWideIPStatistics)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_wideip //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_wideip( string [] aliases ) { object [] results = this.Invoke("get_wideip", new object [] { aliases}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_wideip(string [] aliases, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_wideip", new object[] { aliases}, callback, asyncState); } public string [] [] Endget_wideip(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_wideip_pool //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBWideIPWideIPPool [] [] get_wideip_pool( string [] wide_ips ) { object [] results = this.Invoke("get_wideip_pool", new object [] { wide_ips}); return ((GlobalLBWideIPWideIPPool [] [])(results[0])); } public System.IAsyncResult Beginget_wideip_pool(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_wideip_pool", new object[] { wide_ips}, callback, asyncState); } public GlobalLBWideIPWideIPPool [] [] Endget_wideip_pool(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBWideIPWideIPPool [] [])(results[0])); } //----------------------------------------------------------------------- // get_wideip_rule //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBWideIPWideIPRule [] [] get_wideip_rule( string [] wide_ips ) { object [] results = this.Invoke("get_wideip_rule", new object [] { wide_ips}); return ((GlobalLBWideIPWideIPRule [] [])(results[0])); } public System.IAsyncResult Beginget_wideip_rule(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_wideip_rule", new object[] { wide_ips}, callback, asyncState); } public GlobalLBWideIPWideIPRule [] [] Endget_wideip_rule(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBWideIPWideIPRule [] [])(results[0])); } //----------------------------------------------------------------------- // remove_alias //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void remove_alias( string [] wide_ips, string [] [] aliases ) { this.Invoke("remove_alias", new object [] { wide_ips, aliases}); } public System.IAsyncResult Beginremove_alias(string [] wide_ips,string [] [] aliases, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_alias", new object[] { wide_ips, aliases}, callback, asyncState); } public void Endremove_alias(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_all_aliases //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void remove_all_aliases( string [] wide_ips ) { this.Invoke("remove_all_aliases", new object [] { wide_ips}); } public System.IAsyncResult Beginremove_all_aliases(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_aliases", new object[] { wide_ips}, callback, asyncState); } public void Endremove_all_aliases(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_all_metadata //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void remove_all_metadata( string [] wide_ips ) { this.Invoke("remove_all_metadata", new object [] { wide_ips}); } public System.IAsyncResult Beginremove_all_metadata(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_metadata", new object[] { wide_ips}, callback, asyncState); } public void Endremove_all_metadata(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_all_wideip_pools //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void remove_all_wideip_pools( string [] wide_ips ) { this.Invoke("remove_all_wideip_pools", new object [] { wide_ips}); } public System.IAsyncResult Beginremove_all_wideip_pools(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_wideip_pools", new object[] { wide_ips}, callback, asyncState); } public void Endremove_all_wideip_pools(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_all_wideip_rules //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void remove_all_wideip_rules( string [] wide_ips ) { this.Invoke("remove_all_wideip_rules", new object [] { wide_ips}); } public System.IAsyncResult Beginremove_all_wideip_rules(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_wideip_rules", new object[] { wide_ips}, callback, asyncState); } public void Endremove_all_wideip_rules(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_metadata //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void remove_metadata( string [] wide_ips, string [] [] names ) { this.Invoke("remove_metadata", new object [] { wide_ips, names}); } public System.IAsyncResult Beginremove_metadata(string [] wide_ips,string [] [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_metadata", new object[] { wide_ips, names}, callback, asyncState); } public void Endremove_metadata(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_wideip_pool //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void remove_wideip_pool( string [] wide_ips, GlobalLBWideIPWideIPPool [] [] wideip_pools ) { this.Invoke("remove_wideip_pool", new object [] { wide_ips, wideip_pools}); } public System.IAsyncResult Beginremove_wideip_pool(string [] wide_ips,GlobalLBWideIPWideIPPool [] [] wideip_pools, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_wideip_pool", new object[] { wide_ips, wideip_pools}, callback, asyncState); } public void Endremove_wideip_pool(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_wideip_rule //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void remove_wideip_rule( string [] wide_ips, GlobalLBWideIPWideIPRule [] [] wideip_rules ) { this.Invoke("remove_wideip_rule", new object [] { wide_ips, wideip_rules}); } public System.IAsyncResult Beginremove_wideip_rule(string [] wide_ips,GlobalLBWideIPWideIPRule [] [] wideip_rules, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_wideip_rule", new object[] { wide_ips, wideip_rules}, callback, asyncState); } public void Endremove_wideip_rule(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_application //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void reset_application( string [] wide_ips ) { this.Invoke("reset_application", new object [] { wide_ips}); } public System.IAsyncResult Beginreset_application(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_application", new object[] { wide_ips}, callback, asyncState); } public void Endreset_application(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void reset_statistics( string [] wide_ips ) { this.Invoke("reset_statistics", new object [] { wide_ips}); } public System.IAsyncResult Beginreset_statistics(string [] wide_ips, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { wide_ips}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_application //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_application( string [] wide_ips, string [] applications ) { this.Invoke("set_application", new object [] { wide_ips, applications}); } public System.IAsyncResult Beginset_application(string [] wide_ips,string [] applications, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_application", new object[] { wide_ips, applications}, callback, asyncState); } public void Endset_application(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_description( string [] wide_ips, string [] descriptions ) { this.Invoke("set_description", new object [] { wide_ips, descriptions}); } public System.IAsyncResult Beginset_description(string [] wide_ips,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { wide_ips, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_enabled_state( string [] wide_ips, CommonEnabledState [] states ) { this.Invoke("set_enabled_state", new object [] { wide_ips, states}); } public System.IAsyncResult Beginset_enabled_state(string [] wide_ips,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_enabled_state", new object[] { wide_ips, states}, callback, asyncState); } public void Endset_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ipv6_no_error_negative_ttl //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_ipv6_no_error_negative_ttl( string [] wide_ips, long [] values ) { this.Invoke("set_ipv6_no_error_negative_ttl", new object [] { wide_ips, values}); } public System.IAsyncResult Beginset_ipv6_no_error_negative_ttl(string [] wide_ips,long [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ipv6_no_error_negative_ttl", new object[] { wide_ips, values}, callback, asyncState); } public void Endset_ipv6_no_error_negative_ttl(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ipv6_no_error_response_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_ipv6_no_error_response_state( string [] wide_ips, CommonEnabledState [] states ) { this.Invoke("set_ipv6_no_error_response_state", new object [] { wide_ips, states}); } public System.IAsyncResult Beginset_ipv6_no_error_response_state(string [] wide_ips,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ipv6_no_error_response_state", new object[] { wide_ips, states}, callback, asyncState); } public void Endset_ipv6_no_error_response_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_last_resort_pool //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_last_resort_pool( string [] wide_ips, string [] pool_names ) { this.Invoke("set_last_resort_pool", new object [] { wide_ips, pool_names}); } public System.IAsyncResult Beginset_last_resort_pool(string [] wide_ips,string [] pool_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_last_resort_pool", new object[] { wide_ips, pool_names}, callback, asyncState); } public void Endset_last_resort_pool(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_lb_decision_log_verbosity //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_lb_decision_log_verbosity( string [] wide_ips, GlobalLBWideIPLBDecisionLogVerbosity [] [] verbosities ) { this.Invoke("set_lb_decision_log_verbosity", new object [] { wide_ips, verbosities}); } public System.IAsyncResult Beginset_lb_decision_log_verbosity(string [] wide_ips,GlobalLBWideIPLBDecisionLogVerbosity [] [] verbosities, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_lb_decision_log_verbosity", new object[] { wide_ips, verbosities}, callback, asyncState); } public void Endset_lb_decision_log_verbosity(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_lb_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_lb_method( string [] wide_ips, GlobalLBLBMethod [] lb_methods ) { this.Invoke("set_lb_method", new object [] { wide_ips, lb_methods}); } public System.IAsyncResult Beginset_lb_method(string [] wide_ips,GlobalLBLBMethod [] lb_methods, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_lb_method", new object[] { wide_ips, lb_methods}, callback, asyncState); } public void Endset_lb_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_metadata_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_metadata_description( string [] wide_ips, string [] [] names, string [] [] descriptions ) { this.Invoke("set_metadata_description", new object [] { wide_ips, names, descriptions}); } public System.IAsyncResult Beginset_metadata_description(string [] wide_ips,string [] [] names,string [] [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_metadata_description", new object[] { wide_ips, names, descriptions}, callback, asyncState); } public void Endset_metadata_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_metadata_persistence //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_metadata_persistence( string [] wide_ips, string [] [] names, CommonMetadataPersistence [] [] values ) { this.Invoke("set_metadata_persistence", new object [] { wide_ips, names, values}); } public System.IAsyncResult Beginset_metadata_persistence(string [] wide_ips,string [] [] names,CommonMetadataPersistence [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_metadata_persistence", new object[] { wide_ips, names, values}, callback, asyncState); } public void Endset_metadata_persistence(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_metadata_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_metadata_value( string [] wide_ips, string [] [] names, string [] [] values ) { this.Invoke("set_metadata_value", new object [] { wide_ips, names, values}); } public System.IAsyncResult Beginset_metadata_value(string [] wide_ips,string [] [] names,string [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_metadata_value", new object[] { wide_ips, names, values}, callback, asyncState); } public void Endset_metadata_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_persistence_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_persistence_state( string [] wide_ips, CommonEnabledState [] states ) { this.Invoke("set_persistence_state", new object [] { wide_ips, states}); } public System.IAsyncResult Beginset_persistence_state(string [] wide_ips,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_persistence_state", new object[] { wide_ips, states}, callback, asyncState); } public void Endset_persistence_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_persistence_ttl //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIP", RequestNamespace="urn:iControl:GlobalLB/WideIP", ResponseNamespace="urn:iControl:GlobalLB/WideIP")] public void set_persistence_ttl( string [] wide_ips, long [] values ) { this.Invoke("set_persistence_ttl", new object [] { wide_ips, values}); } public System.IAsyncResult Beginset_persistence_ttl(string [] wide_ips,long [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_persistence_ttl", new object[] { wide_ips, values}, callback, asyncState); } public void Endset_persistence_ttl(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.WideIP.LBDecisionLogVerbosity", Namespace = "urn:iControl")] public enum GlobalLBWideIPLBDecisionLogVerbosity { LB_DECISION_LOG_UNKNOWN, LB_DECISION_LOG_NONE, LB_DECISION_POOL_SELECTION, LB_DECISION_POOL_TRAVERSAL, LB_DECISION_PM_SELECTION, LB_DECISION_PM_TRAVERSAL, LB_DECISION_LOG_ALL, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.WideIP.WideIPPool", Namespace = "urn:iControl")] public partial class GlobalLBWideIPWideIPPool { private string pool_nameField; public string pool_name { get { return this.pool_nameField; } set { this.pool_nameField = value; } } private long orderField; public long order { get { return this.orderField; } set { this.orderField = value; } } private long ratioField; public long ratio { get { return this.ratioField; } set { this.ratioField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.WideIP.WideIPRule", Namespace = "urn:iControl")] public partial class GlobalLBWideIPWideIPRule { private string rule_nameField; public string rule_name { get { return this.rule_nameField; } set { this.rule_nameField = value; } } private long priorityField; public long priority { get { return this.priorityField; } set { this.priorityField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.WideIP.WideIPStatisticEntry", Namespace = "urn:iControl")] public partial class GlobalLBWideIPWideIPStatisticEntry { private string wide_ipField; public string wide_ip { get { return this.wide_ipField; } set { this.wide_ipField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.WideIP.WideIPStatistics", Namespace = "urn:iControl")] public partial class GlobalLBWideIPWideIPStatistics { private GlobalLBWideIPWideIPStatisticEntry [] statisticsField; public GlobalLBWideIPWideIPStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
/* * 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 Newtonsoft.Json; using QuantConnect.Orders; using QuantConnect.Securities; using RestSharp; using System; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.Linq; using System.Net; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Logging; using QuantConnect.Orders.Fees; using QuantConnect.Util; namespace QuantConnect.Brokerages.GDAX { public partial class GDAXBrokerage : BaseWebsocketsBrokerage { private const int MaxDataPointsPerHistoricalRequest = 300; // These are the only currencies accepted for fiat deposits private static readonly HashSet<string> FiatCurrencies = new List<string> { Currencies.EUR, Currencies.GBP, Currencies.USD }.ToHashSet(); #region IBrokerage /// <summary> /// Checks if the websocket connection is connected or in the process of connecting /// </summary> public override bool IsConnected => WebSocket.IsOpen; /// <summary> /// Creates a new order /// </summary> /// <param name="order"></param> /// <returns></returns> public override bool PlaceOrder(Order order) { var req = new RestRequest("/orders", Method.POST); dynamic payload = new ExpandoObject(); payload.size = Math.Abs(order.Quantity); payload.side = order.Direction.ToLower(); payload.type = ConvertOrderType(order.Type); if (order.Type != OrderType.Market) { payload.price = (order as LimitOrder)?.LimitPrice ?? (order as StopLimitOrder)?.LimitPrice ?? (order as StopMarketOrder)?.StopPrice ?? 0; } payload.product_id = _symbolMapper.GetBrokerageSymbol(order.Symbol); if (_algorithm.BrokerageModel.AccountType == AccountType.Margin) { payload.overdraft_enabled = true; } var orderProperties = order.Properties as GDAXOrderProperties; if (orderProperties != null) { if (order.Type == OrderType.Limit) { payload.post_only = orderProperties.PostOnly; } } if (order.Type == OrderType.StopLimit) { payload.stop = order.Direction == OrderDirection.Buy ? "entry" : "loss"; payload.stop_price = (order as StopLimitOrder).StopPrice; } var json = JsonConvert.SerializeObject(payload); Log.Trace($"GDAXBrokerage.PlaceOrder(): {json}"); req.AddJsonBody(json); GetAuthenticationToken(req); var response = ExecuteRestRequest(req, GdaxEndpointType.Private); var orderFee = OrderFee.Zero; if (response.StatusCode == HttpStatusCode.OK && response.Content != null) { var raw = JsonConvert.DeserializeObject<Messages.Order>(response.Content); if (raw?.Id == null) { var errorMessage = $"Error parsing response from place order: {response.Content}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "GDAX Order Event") { Status = OrderStatus.Invalid, Message = errorMessage }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, (int)response.StatusCode, errorMessage)); return true; } if (raw.Status == "rejected") { var errorMessage = "Reject reason: " + raw.RejectReason; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "GDAX Order Event") { Status = OrderStatus.Invalid, Message = errorMessage }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, (int)response.StatusCode, errorMessage)); return true; } var brokerId = raw.Id; if (CachedOrderIDs.ContainsKey(order.Id)) { CachedOrderIDs[order.Id].BrokerId.Add(brokerId); } else { order.BrokerId.Add(brokerId); CachedOrderIDs.TryAdd(order.Id, order); } // Add fill splits in all cases; we'll need to handle market fills too. FillSplit.TryAdd(order.Id, new GDAXFill(order)); // Generate submitted event OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "GDAX Order Event") { Status = OrderStatus.Submitted }); Log.Trace($"Order submitted successfully - OrderId: {order.Id}"); _pendingOrders.TryAdd(brokerId, new PendingOrder(order)); _fillMonitorResetEvent.Set(); return true; } var message = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {response.Content}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "GDAX Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, message)); return true; } /// <summary> /// This operation is not supported /// </summary> /// <param name="order"></param> /// <returns></returns> public override bool UpdateOrder(Order order) { throw new NotSupportedException("GDAXBrokerage.UpdateOrder: Order update not supported. Please cancel and re-create."); } /// <summary> /// Cancels an order /// </summary> /// <param name="order"></param> /// <returns></returns> public override bool CancelOrder(Order order) { var success = new List<bool>(); foreach (var id in order.BrokerId) { var req = new RestRequest("/orders/" + id, Method.DELETE); GetAuthenticationToken(req); var response = ExecuteRestRequest(req, GdaxEndpointType.Private); success.Add(response.StatusCode == HttpStatusCode.OK); if (response.StatusCode == HttpStatusCode.OK) { OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "GDAX Order Event") { Status = OrderStatus.Canceled }); PendingOrder orderRemoved; _pendingOrders.TryRemove(id, out orderRemoved); } } return success.All(a => a); } /// <summary> /// Connects the client to the broker's remote servers /// </summary> public override void Connect() { base.Connect(); AccountBaseCurrency = GetAccountBaseCurrency(); } /// <summary> /// Closes the websockets connection /// </summary> public override void Disconnect() { if (!_canceller.IsCancellationRequested) { _canceller.Cancel(); } WebSocket.Close(); } /// <summary> /// Gets all orders not yet closed /// </summary> /// <returns></returns> public override List<Order> GetOpenOrders() { var list = new List<Order>(); var req = new RestRequest("/orders?status=open&status=pending&status=active", Method.GET); GetAuthenticationToken(req); var response = ExecuteRestRequest(req, GdaxEndpointType.Private); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"GDAXBrokerage.GetOpenOrders: request failed: [{(int) response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}"); } var orders = JsonConvert.DeserializeObject<Messages.Order[]>(response.Content); foreach (var item in orders) { Order order; if (item.Type == "market") { order = new MarketOrder { Price = item.Price }; } else if (!string.IsNullOrEmpty(item.Stop)) { order = new StopLimitOrder { StopPrice = item.StopPrice, LimitPrice = item.Price }; } else if (item.Type == "limit") { order = new LimitOrder { LimitPrice = item.Price }; } else if (item.Type == "stop") { order = new StopMarketOrder { StopPrice = item.Price }; } else { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (int)response.StatusCode, "GDAXBrokerage.GetOpenOrders: Unsupported order type returned from brokerage: " + item.Type)); continue; } order.Quantity = item.Side == "sell" ? -item.Size : item.Size; order.BrokerId = new List<string> { item.Id }; order.Symbol = _symbolMapper.GetLeanSymbol(item.ProductId, SecurityType.Crypto, Market.GDAX); order.Time = DateTime.UtcNow; order.Status = ConvertOrderStatus(item); order.Price = item.Price; list.Add(order); } foreach (var item in list) { if (item.Status.IsOpen()) { var cached = CachedOrderIDs.Where(c => c.Value.BrokerId.Contains(item.BrokerId.First())); if (cached.Any()) { CachedOrderIDs[cached.First().Key] = item; } } } return list; } /// <summary> /// Gets all open positions /// </summary> /// <returns></returns> public override List<Holding> GetAccountHoldings() { /* * On launching the algorithm the cash balances are pulled and stored in the cashbook. * Try loading pre-existing currency swaps from the job packet if provided */ return base.GetAccountHoldings(_job?.BrokerageData, _algorithm?.Securities.Values); } /// <summary> /// Gets the total account cash balance /// </summary> /// <returns></returns> public override List<CashAmount> GetCashBalance() { var list = new List<CashAmount>(); var request = new RestRequest("/accounts", Method.GET); GetAuthenticationToken(request); var response = ExecuteRestRequest(request, GdaxEndpointType.Private); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"GDAXBrokerage.GetCashBalance: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}"); } foreach (var item in JsonConvert.DeserializeObject<Messages.Account[]>(response.Content)) { if (item.Balance > 0) { list.Add(new CashAmount(item.Balance, item.Currency.ToUpperInvariant())); } } return list; } /// <summary> /// Gets the history for the requested security /// </summary> /// <param name="request">The historical data request</param> /// <returns>An enumerable of bars covering the span specified in the request</returns> public override IEnumerable<BaseData> GetHistory(HistoryRequest request) { // GDAX API only allows us to support history requests for TickType.Trade if (request.TickType != TickType.Trade) { yield break; } if (!_symbolMapper.IsKnownLeanSymbol(request.Symbol)) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidSymbol", $"Unknown symbol: {request.Symbol.Value}, no history returned")); yield break; } if (request.EndTimeUtc < request.StartTimeUtc) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidDateRange", "The history request start date must precede the end date, no history returned")); yield break; } if (request.Resolution == Resolution.Tick || request.Resolution == Resolution.Second) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidResolution", $"{request.Resolution} resolution not supported, no history returned")); yield break; } Log.Trace($"GDAXBrokerage.GetHistory(): Submitting request: {request.Symbol.Value}: {request.Resolution} {request.StartTimeUtc} UTC -> {request.EndTimeUtc} UTC"); foreach (var tradeBar in GetHistoryFromCandles(request)) { yield return tradeBar; } } /// <summary> /// Returns TradeBars from GDAX candles (only for Minute/Hour/Daily resolutions) /// </summary> /// <param name="request">The history request instance</param> private IEnumerable<TradeBar> GetHistoryFromCandles(HistoryRequest request) { var productId = _symbolMapper.GetBrokerageSymbol(request.Symbol); var granularity = Convert.ToInt32(request.Resolution.ToTimeSpan().TotalSeconds); var startTime = request.StartTimeUtc; var endTime = request.EndTimeUtc; var maximumRange = TimeSpan.FromSeconds(MaxDataPointsPerHistoricalRequest * granularity); do { var maximumEndTime = startTime.Add(maximumRange); if (endTime > maximumEndTime) { endTime = maximumEndTime; } var restRequest = new RestRequest($"/products/{productId}/candles?start={startTime:o}&end={endTime:o}&granularity={granularity}", Method.GET); var response = ExecuteRestRequest(restRequest, GdaxEndpointType.Public); if (response.StatusCode != HttpStatusCode.OK) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "HistoryError", $"History request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}")); yield break; } var bars = ParseCandleData(request.Symbol, granularity, response.Content, startTime); TradeBar lastPointReceived = null; foreach (var datapoint in bars.OrderBy(x => x.Time)) { lastPointReceived = datapoint; yield return datapoint; } startTime = lastPointReceived?.EndTime ?? request.EndTimeUtc; endTime = request.EndTimeUtc; } while (startTime < request.EndTimeUtc); } /// <summary> /// Parse TradeBars from JSON response /// https://docs.pro.coinbase.com/#get-historic-rates /// </summary> private static IEnumerable<TradeBar> ParseCandleData(Symbol symbol, int granularity, string data, DateTime startTimeUtc) { if (data.Length == 0) { yield break; } var parsedData = JsonConvert.DeserializeObject<string[][]>(data); var period = TimeSpan.FromSeconds(granularity); foreach (var datapoint in parsedData) { var time = Time.UnixTimeStampToDateTime(double.Parse(datapoint[0], CultureInfo.InvariantCulture)); if (time < startTimeUtc) { // Note from GDAX docs: // If data points are readily available, your response may contain as many as 300 candles // and some of those candles may precede your declared start value. yield break; } var close = datapoint[4].ToDecimal(); yield return new TradeBar { Symbol = symbol, Time = time, Period = period, Open = datapoint[3].ToDecimal(), High = datapoint[2].ToDecimal(), Low = datapoint[1].ToDecimal(), Close = close, Value = close, Volume = decimal.Parse(datapoint[5], NumberStyles.Float, CultureInfo.InvariantCulture) }; } } #endregion /// <summary> /// Gets the account base currency /// </summary> private string GetAccountBaseCurrency() { var req = new RestRequest("/accounts", Method.GET); GetAuthenticationToken(req); var response = ExecuteRestRequest(req, GdaxEndpointType.Private); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"GDAXBrokerage.GetAccountBaseCurrency(): request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}"); } var result = JsonConvert.DeserializeObject<Messages.Account[]>(response.Content) .Where(account => FiatCurrencies.Contains(account.Currency)) // we choose the first fiat currency which has the largest available quantity .OrderByDescending(account => account.Available).ThenBy(account => account.Currency) .FirstOrDefault()?.Currency; return result ?? Currencies.USD; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { _ctsFillMonitor.Cancel(); _fillMonitorTask.Wait(TimeSpan.FromSeconds(5)); _canceller.DisposeSafely(); _aggregator.DisposeSafely(); _publicEndpointRateLimiter.Dispose(); _privateEndpointRateLimiter.Dispose(); } } }
using System.Text; using System; namespace SharpLua.LASM { /// <summary> /// Some bit manipulations for binary chunks /// </summary> public class Bit { //new = function(str) // return tonumber(str, 2) //end, /* Broken :( Lets use the Lua API Instead... public static int Get(long num, int n) { double pn = Math.Pow(2, (n - 1)); return (num % (pn + pn) >= pn) ? 1 : 0; } public static long Get(long num, int n, int n2) { long total = 0; long digitn = 0; for (int i = n; i </ *=* / n2; i++) { Console.WriteLine(">" + i); //total += (long)Math.Pow(2, digitn * Bit.Get(num, i)); total += (long)Math.Pow(2, digitn) * Bit.Get(num, i); digitn++; } return total; } public static string GetString(long num, int mindigit = 0, string sep = "-") { int pow = 0; long tot = 1; while (tot <= num) { tot = tot * 2; pow = pow + 1; } if (pow < mindigit) pow = mindigit; string str = ""; for (int i = pow; i > 1; i--) str = str + Bit.Get(num, i) + (i == 1 ? "" : sep); return str; } */ public static readonly int[] p2 = new int[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072 }; public static long keep(long x, int n) { return x % p2[n]; } public static long srb(long x, int n) { return (long)Math.Floor((double)x / p2[n]);// + 1]); } public static long slb(long x, int n) { return x * p2[n];// + 1]; } public static double ldexp(double val, int exp) { return (val * (Math.Pow(2, exp))); } /// <summary> /// Class to store frexp results /// </summary> public class FRexpResult { public int exponent = 0; public double mantissa = 0; } /// <summary> /// math.frexp implementation in C# /// </summary> /// <param name="value"></param> /// <returns></returns> public static FRexpResult frexp(double value) { FRexpResult result = new FRexpResult(); long bits = BitConverter.DoubleToInt64Bits(value); double realMant = 1; // Test for NaN, infinity, and zero. if (Double.IsNaN(value) || value + value == value || Double.IsInfinity(value)) { result.exponent = 0; result.mantissa = value; } else { bool neg = (bits < 0); int exponent = (int)((bits >> 52) & 0x7ffL); long mantissa = bits & 0xfffffffffffffL; if (exponent == 0) { exponent++; } else { mantissa = mantissa | (1L << 52); } // bias the exponent - actually biased by 1023. // we are treating the mantissa as m.0 instead of 0.m // so subtract another 52. exponent -= 1075; realMant = mantissa; // normalize while (realMant > 1.0) { mantissa >>= 1; realMant /= 2; exponent++; } if (neg) { realMant = realMant * -1; } result.exponent = exponent; result.mantissa = realMant; } return result; } } /* class DumpBinary { // This is... bad. Only supports X86 Standard public static String DumpString(string s) if #s != 0 then return DumpBinary.Int32(#s+1)..s.."\0"); else return "\0\0\0\0"; end end, Integer = function(n) return DumpBinary.Int32(n) end,]] Int8 = function(n) return string.char(n) end,--[[ Int16 = function(n) error("DumpBinary::Int16() Not Implemented") end, Int32 = function(x) local v = "" x = math.floor(x) if x >= 0 then for i = 1, 4 do v = v..string.char(x % 256) x = math.floor(x / 256) end else -- x < 0 x = -x local carry = 1 for i = 1, 4 do local c = 255 - (x % 256) + carry if c == 256 then c = 0; carry = 1 else carry = 0 end v = v..string.char(c) x = math.floor(x / 256) end end return v end, Float64 = function(x) local function grab_byte(v) return math.floor(v / 256), string.char(math.floor(v) % 256) end local sign = 0 if x < 0 then sign = 1; x = -x end local mantissa, exponent = math.frexp(x) if x == 0 then -- zero mantissa, exponent = 0, 0 elseif x == 1/0 then mantissa, exponent = 0, 2047 else mantissa = (mantissa * 2 - 1) * math.ldexp(0.5, 53) exponent = exponent + 1022 end local v, byte = "" -- convert to bytes x = mantissa for i = 1,6 do x, byte = grab_byte(x) v = v..byte -- 47:0 end x, byte = grab_byte(exponent * 16 + x) v = v..byte -- 55:48 x, byte = grab_byte(sign * 128 + x) v = v..byte -- 63:56 return v end,]] }*/ /// <summary> /// Dumps an instruction/opcode into a 4-char string /// </summary> public class DumpBinary { public static string Opcode(Instruction op) { long c0, c1, c2, c3; if (op.OpcodeType == OpcodeType.AsBx) { long Bx = op.sBx + 131071; long C = Bit.keep(Bx, 9); long B = Bit.srb(Bx, 9); c0 = op.OpcodeNumber + Bit.slb(Bit.keep(op.A, 2), 6); c1 = Bit.srb(op.A, 2) + Bit.slb(Bit.keep(C, 2), 6); c2 = Bit.srb(C, 2) + Bit.slb(Bit.keep(B, 1), 7); c3 = Bit.srb(B, 1); } else if (op.OpcodeType == OpcodeType.ABx) { long C = Bit.keep(op.Bx, 9); long B = Bit.srb(op.Bx, 9); c0 = op.OpcodeNumber + Bit.slb(Bit.keep(op.A, 2), 6); c1 = Bit.srb(op.A, 2) + Bit.slb(Bit.keep(C, 2), 6); c2 = Bit.srb(C, 2) + Bit.slb(Bit.keep(B, 1), 7); c3 = Bit.srb(B, 1); } else { c0 = op.OpcodeNumber + Bit.slb(Bit.keep(op.A, 2), 6); c1 = Bit.srb(op.A, 2) + Bit.slb(Bit.keep(op.C, 2), 6); c2 = Bit.srb(op.C, 2) + Bit.slb(Bit.keep(op.B, 1), 7); c3 = Bit.srb(op.B, 1); } StringBuilder sb = new StringBuilder(); sb.Append((char)c0); sb.Append((char)c1); sb.Append((char)c2); sb.Append((char)c3); return sb.ToString(); } } }
// 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.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary> /// Creates an array of <see cref="Process"/> components that are associated with process resources on a /// remote computer. These process resources share the specified process name. /// </summary> public static Process[] GetProcessesByName(string processName, string machineName) { if (processName == null) { processName = string.Empty; } Process[] procs = GetProcesses(machineName); var list = new List<Process>(); for (int i = 0; i < procs.Length; i++) { if (string.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase)) { list.Add(procs[i]); } else { procs[i].Dispose(); } } return list.ToArray(); } [CLSCompliant(false)] public static Process Start(string fileName, string userName, SecureString password, string domain) { ProcessStartInfo startInfo = new ProcessStartInfo(fileName); startInfo.UserName = userName; startInfo.Password = password; startInfo.Domain = domain; startInfo.UseShellExecute = false; return Start(startInfo); } [CLSCompliant(false)] public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain) { ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments); startInfo.UserName = userName; startInfo.Password = password; startInfo.Domain = domain; startInfo.UseShellExecute = false; return Start(startInfo); } /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { SetPrivilege(Interop.Advapi32.SeDebugPrivilege, (int)Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED); } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { SetPrivilege(Interop.Advapi32.SeDebugPrivilege, 0); } /// <summary>Terminates the associated process immediately.</summary> public void Kill() { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_TERMINATE)) { if (!Interop.Kernel32.TerminateProcess(handle, -1)) throw new Win32Exception(); } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { _signaled = false; } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { // Nop } /// <devdoc> /// Make sure we are watching for a process exit. /// </devdoc> /// <internalonly/> private void EnsureWatchingForExit() { if (!_watchingForExit) { lock (this) { if (!_watchingForExit) { Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle"); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try { _waitHandle = new Interop.Kernel32.ProcessWaitHandle(_processHandle); _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(CompletionCallback), _waitHandle, -1, true); } catch { _watchingForExit = false; throw; } } } } } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false); if (handle.IsInvalid) return true; using (Interop.Kernel32.ProcessWaitHandle processWaitHandle = new Interop.Kernel32.ProcessWaitHandle(handle)) { return _signaled = processWaitHandle.WaitOne(milliseconds); } } finally { // If we have a hard timeout, we cannot wait for the streams if (_output != null && milliseconds == Timeout.Infinite) _output.WaitUtilEOF(); if (_error != null && milliseconds == Timeout.Infinite) _error.WaitUtilEOF(); handle?.Dispose(); } } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { // We only return null if we couldn't find a main module. This could be because // the process hasn't finished loading the main module (most likely). // On NT, the first module is the main module. EnsureState(State.HaveId | State.IsLocal); return NtProcessManager.GetFirstModule(_processId); } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { using (SafeProcessHandle handle = GetProcessHandle( Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION | Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false)) { if (handle.IsInvalid) { _exited = true; } else { int localExitCode; // Although this is the wrong way to check whether the process has exited, // it was historically the way we checked for it, and a lot of code then took a dependency on // the fact that this would always be set before the pipes were closed, so they would read // the exit code out after calling ReadToEnd() or standard output or standard error. In order // to allow 259 to function as a valid exit code and to break as few people as possible that // took the ReadToEnd dependency, we check for an exit code before doing the more correct // check to see if we have been signaled. if (Interop.Kernel32.GetExitCodeProcess(handle, out localExitCode) && localExitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE) { _exitCode = localExitCode; _exited = true; } else { // The best check for exit is that the kernel process object handle is invalid, // or that it is valid and signaled. Checking if the exit code != STILL_ACTIVE // does not guarantee the process is closed, // since some process could return an actual STILL_ACTIVE exit code (259). if (!_signaled) // if we just came from WaitForExit, don't repeat { using (var wh = new Interop.Kernel32.ProcessWaitHandle(handle)) { _signaled = wh.WaitOne(0); } } if (_signaled) { if (!Interop.Kernel32.GetExitCodeProcess(handle, out localExitCode)) throw new Win32Exception(); _exitCode = localExitCode; _exited = true; } } } } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetProcessTimes().ExitTime; } } /// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary> public TimeSpan PrivilegedProcessorTime { get { return GetProcessTimes().PrivilegedProcessorTime; } } /// <summary>Gets the time the associated process was started.</summary> internal DateTime StartTimeCore { get { return GetProcessTimes().StartTime; } } /// <summary> /// Gets the amount of time the associated process has spent utilizing the CPU. /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>. /// </summary> public TimeSpan TotalProcessorTime { get { return GetProcessTimes().TotalProcessorTime; } } /// <summary> /// Gets the amount of time the associated process has spent running code /// inside the application portion of the process (not the operating system core). /// </summary> public TimeSpan UserProcessorTime { get { return GetProcessTimes().UserProcessorTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { bool disabled; if (!Interop.Kernel32.GetProcessPriorityBoost(handle, out disabled)) { throw new Win32Exception(); } return !disabled; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetProcessPriorityBoost(handle, !value)) throw new Win32Exception(); } } } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int value = Interop.Kernel32.GetPriorityClass(handle); if (value == 0) { throw new Win32Exception(); } return (ProcessPriorityClass)value; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetPriorityClass(handle, (int)value)) throw new Win32Exception(); } } } /// <summary> /// Gets or sets which processors the threads in this process can be scheduled to run on. /// </summary> private IntPtr ProcessorAffinityCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { IntPtr processAffinity, systemAffinity; if (!Interop.Kernel32.GetProcessAffinityMask(handle, out processAffinity, out systemAffinity)) throw new Win32Exception(); return processAffinity; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetProcessAffinityMask(handle, value)) throw new Win32Exception(); } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return unchecked((int)Interop.Kernel32.GetCurrentProcessId()); } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { return GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_ALL_ACCESS); } /// <summary>Get the minimum and maximum working set limits.</summary> private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int ignoredFlags; if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out minWorkingSet, out maxWorkingSet, out ignoredFlags)) throw new Win32Exception(); } } /// <summary>Sets one or both of the minimum and maximum working set limits.</summary> /// <param name="newMin">The new minimum working set limit, or null not to change it.</param> /// <param name="newMax">The new maximum working set limit, or null not to change it.</param> /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param> /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param> private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_SET_QUOTA)) { IntPtr min, max; int ignoredFlags; if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags)) { throw new Win32Exception(); } if (newMin.HasValue) { min = newMin.Value; } if (newMax.HasValue) { max = newMax.Value; } if ((long)min > (long)max) { if (newMin != null) { throw new ArgumentException(SR.BadMinWorkset); } else { throw new ArgumentException(SR.BadMaxWorkset); } } // We use SetProcessWorkingSetSizeEx which gives an option to follow // the max and min value even in low-memory and abundant-memory situations. // However, we do not use these flags to emulate the existing behavior if (!Interop.Kernel32.SetProcessWorkingSetSizeEx(handle, min, max, 0)) { throw new Win32Exception(); } // The value may be rounded/changed by the OS, so go get it if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags)) { throw new Win32Exception(); } resultingMin = min; resultingMax = max; } } /// <summary>Starts the process using the supplied start info.</summary> /// <param name="startInfo">The start info with which to start the process.</param> private unsafe bool StartWithCreateProcess(ProcessStartInfo startInfo) { // See knowledge base article Q190351 for an explanation of the following code. Noteworthy tricky points: // * The handles are duplicated as non-inheritable before they are passed to CreateProcess so // that the child process can not close them // * CreateProcess allows you to redirect all or none of the standard IO handles, so we use // GetStdHandle for the handles that are not being redirected StringBuilder commandLine = BuildCommandLine(startInfo.FileName, StartInfo.Arguments); Process.AppendArguments(commandLine, StartInfo.ArgumentList); Interop.Kernel32.STARTUPINFO startupInfo = new Interop.Kernel32.STARTUPINFO(); Interop.Kernel32.PROCESS_INFORMATION processInfo = new Interop.Kernel32.PROCESS_INFORMATION(); Interop.Kernel32.SECURITY_ATTRIBUTES unused_SecAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); // handles used in parent process SafeFileHandle parentInputPipeHandle = null; SafeFileHandle childInputPipeHandle = null; SafeFileHandle parentOutputPipeHandle = null; SafeFileHandle childOutputPipeHandle = null; SafeFileHandle parentErrorPipeHandle = null; SafeFileHandle childErrorPipeHandle = null; lock (s_createProcessLock) { try { startupInfo.cb = sizeof(Interop.Kernel32.STARTUPINFO); // set up the streams if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) { if (startInfo.RedirectStandardInput) { CreatePipe(out parentInputPipeHandle, out childInputPipeHandle, true); } else { childInputPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE), false); } if (startInfo.RedirectStandardOutput) { CreatePipe(out parentOutputPipeHandle, out childOutputPipeHandle, false); } else { childOutputPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE), false); } if (startInfo.RedirectStandardError) { CreatePipe(out parentErrorPipeHandle, out childErrorPipeHandle, false); } else { childErrorPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE), false); } startupInfo.hStdInput = childInputPipeHandle.DangerousGetHandle(); startupInfo.hStdOutput = childOutputPipeHandle.DangerousGetHandle(); startupInfo.hStdError = childErrorPipeHandle.DangerousGetHandle(); startupInfo.dwFlags = Interop.Advapi32.StartupInfoOptions.STARTF_USESTDHANDLES; } // set up the creation flags parameter int creationFlags = 0; if (startInfo.CreateNoWindow) creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_NO_WINDOW; // set up the environment block parameter string environmentBlock = null; if (startInfo._environmentVariables != null) { creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_UNICODE_ENVIRONMENT; environmentBlock = GetEnvironmentVariablesBlock(startInfo._environmentVariables); } string workingDirectory = startInfo.WorkingDirectory; if (workingDirectory == string.Empty) workingDirectory = Directory.GetCurrentDirectory(); bool retVal; int errorCode = 0; if (startInfo.UserName.Length != 0) { if (startInfo.Password != null && startInfo.PasswordInClearText != null) { throw new ArgumentException(SR.CantSetDuplicatePassword); } Interop.Advapi32.LogonFlags logonFlags = (Interop.Advapi32.LogonFlags)0; if (startInfo.LoadUserProfile) { logonFlags = Interop.Advapi32.LogonFlags.LOGON_WITH_PROFILE; } fixed (char* passwordInClearTextPtr = startInfo.PasswordInClearText ?? string.Empty) fixed (char* environmentBlockPtr = environmentBlock) { IntPtr passwordPtr = (startInfo.Password != null) ? Marshal.SecureStringToGlobalAllocUnicode(startInfo.Password) : IntPtr.Zero; try { retVal = Interop.Advapi32.CreateProcessWithLogonW( startInfo.UserName, startInfo.Domain, (passwordPtr != IntPtr.Zero) ? passwordPtr : (IntPtr)passwordInClearTextPtr, logonFlags, null, // we don't need this since all the info is in commandLine commandLine, creationFlags, (IntPtr)environmentBlockPtr, workingDirectory, ref startupInfo, // pointer to STARTUPINFO ref processInfo // pointer to PROCESS_INFORMATION ); if (!retVal) errorCode = Marshal.GetLastWin32Error(); } finally { if (passwordPtr != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); } } } else { fixed (char* environmentBlockPtr = environmentBlock) { retVal = Interop.Kernel32.CreateProcess( null, // we don't need this since all the info is in commandLine commandLine, // pointer to the command line string ref unused_SecAttrs, // address to process security attributes, we don't need to inherit the handle ref unused_SecAttrs, // address to thread security attributes. true, // handle inheritance flag creationFlags, // creation flags (IntPtr)environmentBlockPtr, // pointer to new environment block workingDirectory, // pointer to current directory name ref startupInfo, // pointer to STARTUPINFO ref processInfo // pointer to PROCESS_INFORMATION ); if (!retVal) errorCode = Marshal.GetLastWin32Error(); } } if (processInfo.hProcess != IntPtr.Zero && processInfo.hProcess != new IntPtr(-1)) procSH.InitialSetHandle(processInfo.hProcess); if (processInfo.hThread != IntPtr.Zero && processInfo.hThread != new IntPtr(-1)) threadSH.InitialSetHandle(processInfo.hThread); if (!retVal) { if (errorCode == Interop.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH) { throw new Win32Exception(errorCode, SR.InvalidApplication); } throw new Win32Exception(errorCode); } } finally { childInputPipeHandle?.Dispose(); childOutputPipeHandle?.Dispose(); childErrorPipeHandle?.Dispose(); threadSH?.Dispose(); } } if (startInfo.RedirectStandardInput) { Encoding enc = startInfo.StandardInputEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleCP()); _standardInput = new StreamWriter(new FileStream(parentInputPipeHandle, FileAccess.Write, 4096, false), enc, 4096); _standardInput.AutoFlush = true; } if (startInfo.RedirectStandardOutput) { Encoding enc = startInfo.StandardOutputEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); _standardOutput = new StreamReader(new FileStream(parentOutputPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096); } if (startInfo.RedirectStandardError) { Encoding enc = startInfo.StandardErrorEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); _standardError = new StreamReader(new FileStream(parentErrorPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096); } if (procSH.IsInvalid) return false; SetProcessHandle(procSH); SetProcessId((int)processInfo.dwProcessId); return true; } private static Encoding GetEncoding(int codePage) { Encoding enc = EncodingHelper.GetSupportedConsoleEncoding(codePage); return new ConsoleEncoding(enc); // ensure encoding doesn't output a preamble } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private bool _signaled; private static StringBuilder BuildCommandLine(string executableFileName, string arguments) { // Construct a StringBuilder with the appropriate command line // to pass to CreateProcess. If the filename isn't already // in quotes, we quote it here. This prevents some security // problems (it specifies exactly which part of the string // is the file to execute). StringBuilder commandLine = new StringBuilder(); string fileName = executableFileName.Trim(); bool fileNameIsQuoted = (fileName.StartsWith("\"", StringComparison.Ordinal) && fileName.EndsWith("\"", StringComparison.Ordinal)); if (!fileNameIsQuoted) { commandLine.Append("\""); } commandLine.Append(fileName); if (!fileNameIsQuoted) { commandLine.Append("\""); } if (!string.IsNullOrEmpty(arguments)) { commandLine.Append(" "); commandLine.Append(arguments); } return commandLine; } /// <summary>Gets timing information for the current process.</summary> private ProcessThreadTimes GetProcessTimes() { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, false)) { if (handle.IsInvalid) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString())); } ProcessThreadTimes processTimes = new ProcessThreadTimes(); if (!Interop.Kernel32.GetProcessTimes(handle, out processTimes._create, out processTimes._exit, out processTimes._kernel, out processTimes._user)) { throw new Win32Exception(); } return processTimes; } } private static unsafe void SetPrivilege(string privilegeName, int attrib) { // this is only a "pseudo handle" to the current process - no need to close it later SafeProcessHandle processHandle = Interop.Kernel32.GetCurrentProcess(); SafeTokenHandle hToken = null; try { // get the process token so we can adjust the privilege on it. We DO need to // close the token when we're done with it. if (!Interop.Advapi32.OpenProcessToken(processHandle, Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out hToken)) { throw new Win32Exception(); } if (!Interop.Advapi32.LookupPrivilegeValue(null, privilegeName, out Interop.Advapi32.LUID luid)) { throw new Win32Exception(); } Interop.Advapi32.TOKEN_PRIVILEGE tp; tp.PrivilegeCount = 1; tp.Privileges.Luid = luid; tp.Privileges.Attributes = (uint)attrib; Interop.Advapi32.AdjustTokenPrivileges(hToken, false, &tp, 0, null, null); // AdjustTokenPrivileges can return true even if it failed to // set the privilege, so we need to use GetLastError if (Marshal.GetLastWin32Error() != Interop.Errors.ERROR_SUCCESS) { throw new Win32Exception(); } } finally { if (hToken != null) { hToken.Dispose(); } } } /// <devdoc> /// Gets a short-term handle to the process, with the given access. /// If a handle is stored in current process object, then use it. /// Note that the handle we stored in current process object will have all access we need. /// </devdoc> /// <internalonly/> private SafeProcessHandle GetProcessHandle(int access, bool throwIfExited) { if (_haveProcessHandle) { if (throwIfExited) { // Since haveProcessHandle is true, we know we have the process handle // open with at least SYNCHRONIZE access, so we can wait on it with // zero timeout to see if the process has exited. using (Interop.Kernel32.ProcessWaitHandle waitHandle = new Interop.Kernel32.ProcessWaitHandle(_processHandle)) { if (waitHandle.WaitOne(0)) { if (_haveProcessId) throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString())); else throw new InvalidOperationException(SR.ProcessHasExitedNoId); } } } // If we dispose of our contained handle we'll be in a bad state. NetFX dealt with this // by doing a try..finally around every usage of GetProcessHandle and only disposed if // it wasn't our handle. return new SafeProcessHandle(_processHandle.DangerousGetHandle(), ownsHandle: false); } else { EnsureState(State.HaveId | State.IsLocal); SafeProcessHandle handle = SafeProcessHandle.InvalidHandle; handle = ProcessManager.OpenProcess(_processId, access, throwIfExited); if (throwIfExited && (access & Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION) != 0) { if (Interop.Kernel32.GetExitCodeProcess(handle, out _exitCode) && _exitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString())); } } return handle; } } /// <devdoc> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </devdoc> /// <internalonly/> private SafeProcessHandle GetProcessHandle(int access) { return GetProcessHandle(access, true); } private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, ref Interop.Kernel32.SECURITY_ATTRIBUTES lpPipeAttributes, int nSize) { bool ret = Interop.Kernel32.CreatePipe(out hReadPipe, out hWritePipe, ref lpPipeAttributes, nSize); if (!ret || hReadPipe.IsInvalid || hWritePipe.IsInvalid) { throw new Win32Exception(); } } // Using synchronous Anonymous pipes for process input/output redirection means we would end up // wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since // it will take advantage of the NT IO completion port infrastructure. But we can't really use // Overlapped I/O for process input/output as it would break Console apps (managed Console class // methods such as WriteLine as well as native CRT functions like printf) which are making an // assumption that the console standard handles (obtained via GetStdHandle()) are opened // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchronously! private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs) { Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributesParent = new Interop.Kernel32.SECURITY_ATTRIBUTES(); securityAttributesParent.bInheritHandle = Interop.BOOL.TRUE; SafeFileHandle hTmp = null; try { if (parentInputs) { CreatePipeWithSecurityAttributes(out childHandle, out hTmp, ref securityAttributesParent, 0); } else { CreatePipeWithSecurityAttributes(out hTmp, out childHandle, ref securityAttributesParent, 0); } // Duplicate the parent handle to be non-inheritable so that the child process // doesn't have access. This is done for correctness sake, exact reason is unclear. // One potential theory is that child process can do something brain dead like // closing the parent end of the pipe and there by getting into a blocking situation // as parent will not be draining the pipe at the other end anymore. SafeProcessHandle currentProcHandle = Interop.Kernel32.GetCurrentProcess(); if (!Interop.Kernel32.DuplicateHandle(currentProcHandle, hTmp, currentProcHandle, out parentHandle, 0, false, Interop.Kernel32.HandleOptions.DUPLICATE_SAME_ACCESS)) { throw new Win32Exception(); } } finally { if (hTmp != null && !hTmp.IsInvalid) { hTmp.Dispose(); } } } private static string GetEnvironmentVariablesBlock(IDictionary<string, string> sd) { // get the keys string[] keys = new string[sd.Count]; sd.Keys.CopyTo(keys, 0); // sort both by the keys // Windows 2000 requires the environment block to be sorted by the key // It will first converting the case the strings and do ordinal comparison. // We do not use Array.Sort(keys, values, IComparer) since it is only supported // in System.Runtime contract from 4.20.0.0 and Test.Net depends on System.Runtime 4.0.10.0 // we workaround this by sorting only the keys and then lookup the values form the keys. Array.Sort(keys, StringComparer.OrdinalIgnoreCase); // create a list of null terminated "key=val" strings StringBuilder stringBuff = new StringBuilder(); for (int i = 0; i < sd.Count; ++i) { stringBuff.Append(keys[i]); stringBuff.Append('='); stringBuff.Append(sd[keys[i]]); stringBuff.Append('\0'); } // an extra null at the end that indicates end of list will come from the string. return stringBuff.ToString(); } } }
// Shows how to use thumbnail functionality of the JPEGator // Copyright (C) 2006-2009, Aleh Dzenisiuk // http://dzenisiuk.info/jpegator/ using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; namespace ThumbnailViewer { /// <summary> /// Summary description for Form1. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.PictureBox pictureBox; private System.Windows.Forms.Label timeLabel; private System.Windows.Forms.TextBox timeTextBox; private System.Windows.Forms.MenuItem openMenuItem; private System.Windows.Forms.MainMenu mainMenu; private System.Windows.Forms.MenuItem fileMenuItem; private System.Windows.Forms.ComboBox qualityComboBox; private System.Windows.Forms.Label qualityLabel; private System.Windows.Forms.CheckBox proportionsCheckBox; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem exitMenuItem; private System.Windows.Forms.TextBox memTextBox; private System.Windows.Forms.Label memLabel; private System.Windows.Forms.Timer memTimer; private System.Windows.Forms.OpenFileDialog openFileDialog; public MainForm() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.mainMenu = new System.Windows.Forms.MainMenu(); this.fileMenuItem = new System.Windows.Forms.MenuItem(); this.openMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.exitMenuItem = new System.Windows.Forms.MenuItem(); this.pictureBox = new System.Windows.Forms.PictureBox(); this.timeLabel = new System.Windows.Forms.Label(); this.timeTextBox = new System.Windows.Forms.TextBox(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.qualityComboBox = new System.Windows.Forms.ComboBox(); this.qualityLabel = new System.Windows.Forms.Label(); this.proportionsCheckBox = new System.Windows.Forms.CheckBox(); this.memTextBox = new System.Windows.Forms.TextBox(); this.memLabel = new System.Windows.Forms.Label(); this.memTimer = new System.Windows.Forms.Timer(); // // mainMenu // this.mainMenu.MenuItems.Add(this.fileMenuItem); // // fileMenuItem // this.fileMenuItem.MenuItems.Add(this.openMenuItem); this.fileMenuItem.MenuItems.Add(this.menuItem1); this.fileMenuItem.MenuItems.Add(this.exitMenuItem); this.fileMenuItem.Text = "File"; // // openMenuItem // this.openMenuItem.Text = "Open..."; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // menuItem1 // this.menuItem1.Text = "-"; // // exitMenuItem // this.exitMenuItem.Text = "Exit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // pictureBox // this.pictureBox.Location = new System.Drawing.Point(36, 8); this.pictureBox.Size = new System.Drawing.Size(168, 168); this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; // // timeLabel // this.timeLabel.Location = new System.Drawing.Point(8, 227); this.timeLabel.Size = new System.Drawing.Size(120, 16); this.timeLabel.Text = "Loading time (ms):"; // // timeTextBox // this.timeTextBox.Location = new System.Drawing.Point(128, 225); this.timeTextBox.ReadOnly = true; this.timeTextBox.Size = new System.Drawing.Size(104, 20); this.timeTextBox.Text = ""; // // openFileDialog // this.openFileDialog.Filter = "JPEG files (*.jpg; *.jpeg) |*.jpg;*.jpeg"; // // qualityComboBox // this.qualityComboBox.Items.Add("Lowest"); this.qualityComboBox.Items.Add("Low"); this.qualityComboBox.Items.Add("High"); this.qualityComboBox.Location = new System.Drawing.Point(128, 179); this.qualityComboBox.Size = new System.Drawing.Size(104, 21); this.qualityComboBox.SelectedIndexChanged += new System.EventHandler(this.qualityComboBox_SelectedIndexChanged); // // qualityLabel // this.qualityLabel.Location = new System.Drawing.Point(8, 181); this.qualityLabel.Size = new System.Drawing.Size(120, 16); this.qualityLabel.Text = "Thumbnail quality:"; // // proportionsCheckBox // this.proportionsCheckBox.Checked = true; this.proportionsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.proportionsCheckBox.Location = new System.Drawing.Point(8, 204); this.proportionsCheckBox.Size = new System.Drawing.Size(224, 16); this.proportionsCheckBox.Text = "Retain proportions"; this.proportionsCheckBox.CheckStateChanged += new System.EventHandler(this.proportionsCheckBox_CheckStateChanged); // // memTextBox // this.memTextBox.Location = new System.Drawing.Point(128, 246); this.memTextBox.ReadOnly = true; this.memTextBox.Size = new System.Drawing.Size(104, 20); this.memTextBox.Text = ""; // // memLabel // this.memLabel.Location = new System.Drawing.Point(8, 246); this.memLabel.Size = new System.Drawing.Size(120, 16); this.memLabel.Text = "Avaiable memory:"; // // memTimer // this.memTimer.Enabled = true; this.memTimer.Interval = 500; this.memTimer.Tick += new System.EventHandler(this.memTimer_Tick); // // MainForm // this.Controls.Add(this.memLabel); this.Controls.Add(this.memTextBox); this.Controls.Add(this.proportionsCheckBox); this.Controls.Add(this.qualityLabel); this.Controls.Add(this.qualityComboBox); this.Controls.Add(this.timeTextBox); this.Controls.Add(this.timeLabel); this.Controls.Add(this.pictureBox); this.MaximizeBox = false; this.Menu = this.mainMenu; this.MinimizeBox = false; this.Text = "Thumbnail Viewer"; this.Load += new System.EventHandler(this.MainForm_Load); } #endregion /// <summary> /// The main entry point for the application. /// </summary> static void Main() { Application.Run(new MainForm()); } // File name or current image private string fileName; // Current thumbnail quality private JPEGator.ThumbnailQuality quality; // Specifies whether to retain proportions of original image private bool proportions = true; private void openMenuItem_Click(object sender, System.EventArgs e) { DialogResult result = openFileDialog.ShowDialog(); if (result == DialogResult.OK) { fileName = openFileDialog.FileName; Reload(); } } private void qualityComboBox_SelectedIndexChanged(object sender, System.EventArgs e) { quality = (JPEGator.ThumbnailQuality)qualityComboBox.SelectedIndex; Reload(); } private void Reload() { if (!System.IO.File.Exists(fileName)) return; Cursor.Current = Cursors.WaitCursor; try { // Remember current tick count to measure loading speed int startTicks = Environment.TickCount; // Create a thumbnail image pictureBox.Image = JPEGator.BitmapUtils.LoadThumbnail( // Put filename of your picture here fileName, // Put here the maximum size of thumbnail image you want to obtain. // If proportional flag is false then this will be an exact size // of thumbnail image, if not then this will be the size corrected // to retain proportions of original image pictureBox.Width, pictureBox.Height, // Select thumbnail quality here: image scaling method and DCT method depend on it; // the lower is quality, the better is speed. quality, // Indicates whether thumbnail image will retain proportions of original image proportions ); // Measure the time in milliseconds, that was needed to load and scale the picture timeTextBox.Text = (Environment.TickCount - startTicks).ToString(); } catch (JPEGator.JpegException ex) { MessageBox.Show( string.Format( "Failed to open {0}: {1}", fileName, ex.Message ), "ThumbnailViewer", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1 ); } finally { Cursor.Current = Cursors.Default; } } private void proportionsCheckBox_CheckStateChanged(object sender, System.EventArgs e) { proportions = proportionsCheckBox.Checked; Reload(); } private void MainForm_Load(object sender, System.EventArgs e) { qualityComboBox.SelectedIndex = 0; } private void exitMenuItem_Click(object sender, System.EventArgs e) { Close(); } private void memTimer_Tick(object sender, System.EventArgs e) { MemoryStatus memStatus = new MemoryStatus(); memStatus.Length = Marshal.SizeOf(memStatus); GlobalMemoryStatus(ref memStatus); memTextBox.Text = string.Format( "{0} Kb", memStatus.AvailVirtual / 1024 ); } private struct MemoryStatus { public int Length; public int MemoryLoad; public int TotalPhys; public int AvailPhys; public int TotalPageFile; public int AvailPageFile; public int TotalVirtual; public int AvailVirtual; } [DllImport("coredll.dll")] private static extern void GlobalMemoryStatus(ref MemoryStatus status); } }
// Based on http://www.coldcity.com/index.php/simple-csharp-raytracer/ // Original license comment follows /* * simpleray * A simple raytracer for teaching purposes * * IainC, 2009 * License: Do WTF you want * * World coord system: * Origin (0,0,0) is the center of the screen * X increases towards right of screen * Y increases towards top of screen * Z increases into screen * * Enough vector maths to get you through: * - The dot product of two vectors gives the cosine of the angle between them * - Normalisation is scaling a vector to have magnitude 1: makes it a "unit vector" * - To get a unit direction vector from point A to point B, do B-A and normalise the result * - To move n units along a direction vector from an origin, new position = origin + (direction * n) * - To reflect a vector in a surface with a known surface normal: * negativeVec = -vecToReflect; * reflectedVec = normal * (2.0f * negativeVec.Dot(normal)) - negativeVec; */ using System; using System.Drawing; using System.Collections.Generic; using System.Diagnostics; using JSIL.Meta; namespace simpleray { public class Vector3f { public float x, y, z; public Vector3f(float x = 0, float y = 0, float z = 0) { this.x = x; this.y = y; this.z = z; } public float Dot(Vector3f b) { return (x * b.x + y * b.y + z * b.z); } public void Normalise() { float f = (float)(1.0f / Math.Sqrt(this.Dot(this))); x *= f; y *= f; z *= f; } public float Magnitude() { return (float)Math.Sqrt(x*x + y*y + z*z); } public static Vector3f operator -(Vector3f a, Vector3f b) { return new Vector3f(a.x - b.x, a.y - b.y, a.z - b.z); } public static Vector3f operator -(Vector3f a) { return new Vector3f(-a.x, -a.y, -a.z); } public static Vector3f operator *(Vector3f a, float b) { return new Vector3f(a.x * b, a.y * b, a.z * b); } public static Vector3f operator /(Vector3f a, float b) { return new Vector3f(a.x / b, a.y / b, a.z / b); } public static Vector3f operator +(Vector3f a, Vector3f b) { return new Vector3f(a.x + b.x, a.y + b.y, a.z + b.z); } public Vector3f ReflectIn(Vector3f normal) { Vector3f negVector = -this; Vector3f reflectedDir = normal * (2.0f * negVector.Dot(normal)) - negVector; return reflectedDir; } } public class Light { public Vector3f position; public Light(Vector3f p) { position = p; } } public class Ray { public const float WORLD_MAX = 1000.0f; public Vector3f origin; public Vector3f direction; public RTObject closestHitObject; public float closestHitDistance; public Vector3f hitPoint; public Ray(Vector3f o, Vector3f d) { origin = o; direction = d; closestHitDistance = WORLD_MAX; closestHitObject = null; } } public abstract class RTObject { public Color color; public abstract float Intersect(Ray ray); public abstract Vector3f GetSurfaceNormalAtPoint(Vector3f p); } class Sphere : RTObject { // to specify a sphere we need it's position and radius public Vector3f position; public float radius; public Sphere(Vector3f p, float r, Color c) { position = p; radius = r; color = c; } public override float Intersect(Ray ray) { Vector3f lightFromOrigin = position - ray.origin; // dir from origin to us float v = lightFromOrigin.Dot(ray.direction); // cos of angle between dirs from origin to us and from origin to where the ray's pointing float hitDistance = radius * radius + v * v - lightFromOrigin.x * lightFromOrigin.x - lightFromOrigin.y * lightFromOrigin.y - lightFromOrigin.z * lightFromOrigin.z; if (hitDistance < 0) // no hit (do this check now before bothering to do the sqrt below) return -1; hitDistance = v - (float)Math.Sqrt(hitDistance); // get actual hit distance if (hitDistance < 0) return -1; else return (float)hitDistance; } public override Vector3f GetSurfaceNormalAtPoint(Vector3f p) { Vector3f normal = p - position; normal.Normalise(); return normal; } } class Plane : RTObject { public Vector3f normal; public float distance; public Plane(Vector3f n, float d, Color c) { normal = n; distance = d; color = c; } public override float Intersect(Ray ray) { float normalDotRayDir = normal.Dot(ray.direction); if (normalDotRayDir == 0) // Ray is parallel to plane (this early-out won't help very often!) return -1; // Any none-parallel ray will hit the plane at some point - the question now is just // if it in the positive or negative ray direction. float hitDistance = -(normal.Dot(ray.origin) - distance) / normalDotRayDir; if (hitDistance < 0) // Ray dir is negative, ie we're behind the ray's origin return -1; else return hitDistance; } public override Vector3f GetSurfaceNormalAtPoint(Vector3f p) { return normal; // This is of course the same across the entire plane } } class RayTracer { const float PI = 3.1415926536f; // maths constants const float PI_X_2 = 6.2831853072f; const float PI_OVER_2 = 1.5707963268f; const int CANVAS_WIDTH = 640; // output image dimensions const int CANVAS_HEIGHT = 480; const float TINY = 0.0001f; // a very short distance in world space coords const int MAX_DEPTH = 3; // max recursion for reflections const float MATERIAL_DIFFUSE_COEFFICIENT = 0.5f; // material diffuse brightness const float MATERIAL_REFLECTION_COEFFICIENT = 0.5f; // material reflection brightness const float MATERIAL_SPECULAR_COEFFICIENT = 2.0f; // material specular highlight brightness const float MATERIAL_SPECULAR_POWER = 50.0f; // material shininess (higher values=smaller highlights) static Color BG_COLOR = Color.BlueViolet; // scene bg colour static Vector3f eyePos = new Vector3f(0, 0, -5.0f); // eye pos in world space coords static Vector3f screenTopLeftPos = new Vector3f(-6.0f, 4.0f, 0); // top-left corner of screen in world coords static Vector3f screenBottomRightPos = new Vector3f(6.0f, -4.0f, 0); // bottom-right corner of screen in world coords static float pixelWidth, pixelHeight; // dimensions of screen pixel **in world coords** static List<RTObject> objects; // all RTObjects in the scene static List<Light> lights; // all lights static Random random; // global random for repeatability static Stopwatch stopwatch; static double minSpeed = double.MaxValue, maxSpeed = double.MinValue; static List<double> speedSamples; static void Main(string[] args) { // init structures objects = new List<RTObject>(); lights = new List<Light>(); random = new Random(01478650229); stopwatch = new Stopwatch(); speedSamples = new List<double>(); Bitmap canvas = new Bitmap(CANVAS_WIDTH, CANVAS_HEIGHT); // add some objects for (int i = 0; i < 30; i++) { float x = (float)(random.NextDouble() * 10.0f) - 5.0f; // Range -5 to 5 float y = (float)(random.NextDouble() * 10.0f) - 5.0f; // Range -5 to 5 float z = (float)(random.NextDouble() * 10.0f); // Range 0 to 10 Color c = Color.FromArgb(255, random.Next(255), random.Next(255), random.Next(255)); Sphere s = new Sphere(new Vector3f(x, y, z), (float)(random.NextDouble()), c); objects.Add(s); } //Sphere debugSphere = new Sphere(new Vector3f(0, 0, 5.0f), 0.2f, Color.ForestGreen); //objects.Add(debugSphere); Plane floor = new Plane(new Vector3f(0, 1.0f, 0), -10.0f, Color.Aquamarine); objects.Add(floor); // add some lights lights.Add(new Light(new Vector3f(2.0f, 0.0f, 0))); lights.Add(new Light(new Vector3f(0, 10.0f, 7.5f))); // calculate width and height of a pixel in world space coords pixelWidth = (screenBottomRightPos.x - screenTopLeftPos.x) / CANVAS_WIDTH; pixelHeight = (screenTopLeftPos.y - screenBottomRightPos.y) / CANVAS_HEIGHT; // render it int dotPeriod = CANVAS_HEIGHT / 10; System.Console.WriteLine("Rendering...\n"); System.Console.WriteLine("|0%---100%|"); RenderRow(canvas, dotPeriod, 0); // save the pretties canvas.Save("output.png"); } static void RenderRow (System.Drawing.Bitmap canvas, int dotPeriod, int y) { if (y >= CANVAS_HEIGHT) return; if ((y % dotPeriod) == 0) System.Console.Write("*"); stopwatch.Restart(); for (int x = 0; x < CANVAS_WIDTH; x++) { Color c = RenderPixel(x, y); canvas.SetPixel(x, y, c); } var elapsed = stopwatch.ElapsedMilliseconds; double msPerPixel = (double)elapsed / CANVAS_WIDTH; ReportSpeed(msPerPixel); SetTimeout(0, () => RenderRow(canvas, dotPeriod, y + 1) ); } static void ReportSpeed (double msPerPixel) { minSpeed = Math.Min(msPerPixel, minSpeed); maxSpeed = Math.Max(msPerPixel, maxSpeed); speedSamples.Add(msPerPixel); double average = 0; foreach (var d in speedSamples) average += d; average /= speedSamples.Count; WriteSpeedText(String.Format( "min: {0:F3} ms/pixel, max: {1:F3} ms/pixel, avg: {2:F3} ms/pixel", minSpeed, maxSpeed, average )); } [JSReplacement("document.getElementById('speed').innerHTML = $text")] static void WriteSpeedText (string text) { Debug.WriteLine(text); } [JSReplacement("setTimeout($action, $timeoutMs)")] static void SetTimeout (int timeoutMs, Action action) { action(); } // Given a ray with origin and direction set, fill in the intersection info static void CheckIntersection(ref Ray ray) { foreach (RTObject obj in objects) { // loop through objects, test for intersection float hitDistance = obj.Intersect(ray); // check for intersection with this object and find distance if (hitDistance < ray.closestHitDistance && hitDistance > 0) { ray.closestHitObject = obj; // object hit and closest yet found - store it ray.closestHitDistance = hitDistance; } } ray.hitPoint = ray.origin + (ray.direction * ray.closestHitDistance); // also store the point of intersection } // raytrace a pixel (ie, set pixel color to result of a trace of a ray starting from eye position and // passing through the world coords of the pixel) static Color RenderPixel(int x, int y) { // First, calculate direction of the current pixel from eye position float sx = screenTopLeftPos.x + (x * pixelWidth); float sy = screenTopLeftPos.y - (y * pixelHeight); Vector3f eyeToPixelDir = new Vector3f(sx, sy, 0) - eyePos; eyeToPixelDir.Normalise(); // Set up primary (eye) ray Ray ray = new Ray(eyePos, eyeToPixelDir); // And trace it! return Trace(ray, 0); } // given a ray, trace it into the scene and return the colour of the surface it hits // (handles reflections recursively) static Color Trace(Ray ray, int traceDepth) { // See if the ray intersected an object CheckIntersection(ref ray); if (ray.closestHitDistance >= Ray.WORLD_MAX || ray.closestHitObject == null) // No intersection return BG_COLOR; // Got a hit - set initial colour to ambient light float r = 0.15f * ray.closestHitObject.color.R; float g = 0.15f * ray.closestHitObject.color.G; float b = 0.15f * ray.closestHitObject.color.B; // Set up stuff we'll need for shading calcs Vector3f surfaceNormal = ray.closestHitObject.GetSurfaceNormalAtPoint(ray.hitPoint); Vector3f viewerDir = -ray.direction; // Direction back to the viewer (simply negative of ray dir) // Loop through the lights, adding contribution of each foreach (Light light in lights) { Vector3f lightDir = new Vector3f(); float lightDistance; // Find light direction and distance lightDir = light.position - ray.hitPoint; // Get direction to light lightDistance = lightDir.Magnitude(); //lightDir = lightDir / lightDistance; // Light exponential falloff lightDir.Normalise(); // Shadow check: check if this light's visible from the point // NB: Step out slightly from the hitpoint first Ray shadowRay = new Ray(ray.hitPoint + (lightDir * TINY), lightDir); shadowRay.closestHitDistance = lightDistance; // IMPORTANT: We only want it to trace as far as the light! CheckIntersection(ref shadowRay); if (shadowRay.closestHitObject != null) // We hit something -- ignore this light entirely continue; float cosLightAngleWithNormal = surfaceNormal.Dot(lightDir); if (MATERIAL_DIFFUSE_COEFFICIENT > TINY) { // Calculate light's diffuse component - note that this is view independant // Dot product of surface normal and light direction gives cos of angle between them so will be in // range -1 to 1. We use that as a scaling factor; common technique, called "cosine shading". if (cosLightAngleWithNormal <= 0) continue; // Add this light's diffuse contribution to our running totals r += MATERIAL_DIFFUSE_COEFFICIENT * cosLightAngleWithNormal * ray.closestHitObject.color.R; g += MATERIAL_DIFFUSE_COEFFICIENT * cosLightAngleWithNormal * ray.closestHitObject.color.G; b += MATERIAL_DIFFUSE_COEFFICIENT * cosLightAngleWithNormal * ray.closestHitObject.color.B; } if (MATERIAL_SPECULAR_COEFFICIENT > TINY) { // Specular component - dot product of light's reflection vector and viewer direction // Direction to the viewer is simply negative of the ray direction Vector3f lightReflectionDir = surfaceNormal * (cosLightAngleWithNormal * 2) - lightDir; float specularFactor = viewerDir.Dot(lightReflectionDir); if (specularFactor > 0) { // To get smaller, sharper highlights we raise it to a power and multiply it specularFactor = MATERIAL_SPECULAR_COEFFICIENT * (float)Math.Pow(specularFactor, MATERIAL_SPECULAR_POWER); // Add the specular contribution to our running totals r += specularFactor * ray.closestHitObject.color.R; g += specularFactor * ray.closestHitObject.color.G; b += specularFactor * ray.closestHitObject.color.B; } } } // Now do reflection, unless we're too deep if (traceDepth < MAX_DEPTH && MATERIAL_REFLECTION_COEFFICIENT > TINY) { // Set up the reflected ray - notice we move the origin out a tiny bit again Vector3f reflectedDir = ray.direction.ReflectIn(surfaceNormal); Ray reflectionRay = new Ray(ray.hitPoint + reflectedDir * TINY, reflectedDir); // And trace! Color reflectionCol = Trace(reflectionRay, traceDepth + 1); // Add reflection results to running totals, scaling by reflect coeff. r += MATERIAL_REFLECTION_COEFFICIENT * reflectionCol.R; g += MATERIAL_REFLECTION_COEFFICIENT * reflectionCol.G; b += MATERIAL_REFLECTION_COEFFICIENT * reflectionCol.B; } // Clamp RGBs if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; return (Color.FromArgb(255, (int)r, (int)g, (int)b)); } } }
#pragma warning disable 1634, 1691 namespace System.Workflow.ComponentModel.Compiler { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.CodeDom; using System.Text; internal sealed class RTTypeWrapper : Type, ICloneable { #region BoundedTypeArray Comparer private class TypeArrayComparer : IEqualityComparer { #region IEqualityComparer Members bool IEqualityComparer.Equals(object x, object y) { Array xArray = x as Array; Array yArray = y as Array; if (xArray == null || yArray == null || xArray.Rank != 1 || yArray.Rank != 1) return false; bool mismatch = false; if (xArray.Length == yArray.Length) { for (int index = 0; !mismatch && index < xArray.Length; index++) mismatch = (xArray.GetValue(index) != yArray.GetValue(index)); } else { mismatch = true; } return !mismatch; } int IEqualityComparer.GetHashCode(object obj) { return 0; } #endregion } #endregion #region Members and Constructors private Type runtimeType = null; private Type[] typeArgs = null; private ITypeProvider typeProvider = null; private Hashtable memberMapping = new Hashtable(); private Hashtable boundedTypes = new Hashtable(new TypeArrayComparer()); internal RTTypeWrapper(ITypeProvider typeProvider, Type runtimeType) { if (runtimeType == null) throw new ArgumentNullException("runtimeType"); //we dont expect DesignTimeType to be passed to this class for wrapping purposes if (runtimeType.Assembly == null) throw new ArgumentException(SR.GetString(SR.Error_InvalidRuntimeType), "runtimeType"); this.typeProvider = typeProvider; this.runtimeType = runtimeType; } internal ITypeProvider Provider { get { return this.typeProvider; } } private RTTypeWrapper(ITypeProvider typeProvider, Type runtimeType, Type[] typeArgs) { if (runtimeType == null) throw new ArgumentNullException("runtimeType"); //we dont expect DesignTimeType to be passed to this class for wrapping purposes if (runtimeType.Assembly == null) throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentValue), "runtimeType"); this.typeProvider = typeProvider; this.runtimeType = runtimeType; if (!IsGenericTypeDefinition) throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentValue), "runtimeType"); this.typeArgs = new Type[typeArgs.Length]; for (int i = 0; i < typeArgs.Length; i++) { this.typeArgs[i] = typeArgs[i]; if (this.typeArgs[i] == null) throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentValue), "typeArgs"); } } #endregion #region Properties public override int MetadataToken { get { return this.runtimeType.MetadataToken; } } public override Assembly Assembly { get { if (this.typeArgs != null) { foreach (Type type in this.typeArgs) if (type.Assembly == null) return null; } return this.runtimeType.Assembly; } } public override string AssemblyQualifiedName { get { return this.FullName + ", " + this.runtimeType.Assembly.FullName; } } public override Type BaseType { get { return ResolveTypeFromTypeSystem(this.runtimeType.BaseType); } } public override Type DeclaringType { get { if (this.runtimeType.DeclaringType == null) return null; return this.typeProvider.GetType(this.runtimeType.DeclaringType.AssemblyQualifiedName); } } public override string FullName { get { StringBuilder fullName = new StringBuilder(this.runtimeType.FullName); if (this.typeArgs != null && this.typeArgs.Length > 0) { fullName.Append("["); for (int index = 0; index < this.typeArgs.Length; index++) { fullName.Append("["); fullName.Append(this.typeArgs[index].AssemblyQualifiedName); fullName.Append("]"); if (index < (this.typeArgs.Length - 1)) fullName.Append(","); } fullName.Append("]"); } return fullName.ToString(); } } public override Guid GUID { get { return this.runtimeType.GUID; } } public override Module Module { get { return this.runtimeType.Module; } } public override string Name { get { if (IsGenericType && !IsGenericTypeDefinition) return GetGenericTypeDefinition().FullName.Substring(Namespace.Length + 1); else if (Namespace != null) return FullName.Substring(Namespace.Length + 1); else return FullName; } } public override string Namespace { get { return this.runtimeType.Namespace; } } public override RuntimeTypeHandle TypeHandle { get { return this.runtimeType.TypeHandle; } } public override Type UnderlyingSystemType { get { return this.runtimeType.UnderlyingSystemType; } } private bool IsAssignable(Type type1, Type type2) { Type typeTemp1 = ResolveTypeFromTypeSystem(type1); Type typeTemp2 = ResolveTypeFromTypeSystem(type2); return TypeProvider.IsAssignable(typeTemp1, typeTemp2); } internal Type ResolveTypeFromTypeSystem(Type type) { if (type == null) return null; if (type.IsGenericParameter) if (this.typeArgs == null) return type; else type = this.typeArgs[type.GenericParameterPosition]; Type returnType = null; try { if (!String.IsNullOrEmpty(type.AssemblyQualifiedName)) returnType = this.typeProvider.GetType(type.AssemblyQualifiedName); } catch { // Work aroundh: there are certain generic types whch we are not able to resolve // form type system, this fix will make sure that we are in thowse cases returning // the original types } if (returnType == null) returnType = type; if (returnType.IsGenericType) returnType = ResolveGenericTypeFromTypeSystem(returnType); return returnType; } internal Type ResolveGenericTypeFromTypeSystem(Type type) { if (this.runtimeType.IsGenericTypeDefinition) { Type baseType = null; if (!type.IsNested) baseType = this.typeProvider.GetType(type.Namespace + "." + type.Name); else { baseType = type; string baseTypeName = type.Name; while (baseType.DeclaringType != null) { baseType = baseType.DeclaringType; baseTypeName = baseType.Name + "+" + baseTypeName; } baseTypeName = baseType.Namespace + "." + baseTypeName; baseType = this.typeProvider.GetType(baseTypeName); } if (baseType != null) return baseType.MakeGenericType(this.typeArgs); else return type; } else return type; } #endregion #region public methods public override bool Equals(object obj) { Type otherType = obj as Type; if (otherType is RTTypeWrapper) otherType = ((RTTypeWrapper)otherType).runtimeType; return this.runtimeType == otherType; } public override object[] GetCustomAttributes(bool inherit) { return this.runtimeType.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return this.runtimeType.GetCustomAttributes(attributeType, inherit); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { List<ConstructorInfo> ctorInfos = new List<ConstructorInfo>(); foreach (ConstructorInfo ctorInfo in this.runtimeType.GetConstructors(bindingAttr)) ctorInfos.Add(EnsureConstructorWrapped(ctorInfo)); return ctorInfos.ToArray(); } public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { EventInfo eventInfo = this.runtimeType.GetEvent(name, bindingAttr); if (eventInfo != null) eventInfo = EnsureEventWrapped(eventInfo); return eventInfo; } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { List<EventInfo> eventInfos = new List<EventInfo>(); foreach (EventInfo eventInfo in this.runtimeType.GetEvents(bindingAttr)) eventInfos.Add(EnsureEventWrapped(eventInfo)); return eventInfos.ToArray(); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { FieldInfo field = this.runtimeType.GetField(name, bindingAttr); if (field != null) field = EnsureFieldWrapped(field); return field; } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { List<FieldInfo> fieldInfos = new List<FieldInfo>(); foreach (FieldInfo fieldInfo in this.runtimeType.GetFields(bindingAttr)) fieldInfos.Add(EnsureFieldWrapped(fieldInfo)); return fieldInfos.ToArray(); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { List<MethodInfo> methodInfos = new List<MethodInfo>(); foreach (MethodInfo methodInfo in this.runtimeType.GetMethods(bindingAttr)) methodInfos.Add(EnsureMethodWrapped(methodInfo)); return methodInfos.ToArray(); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { List<PropertyInfo> propInfos = new List<PropertyInfo>(); foreach (PropertyInfo propInfo in this.runtimeType.GetProperties(bindingAttr)) propInfos.Add(EnsurePropertyWrapped(propInfo)); return propInfos.ToArray(); } public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { List<MemberInfo> memberInfos = new List<MemberInfo>(); foreach (MemberInfo memberInfo in this.runtimeType.GetMember(name, type, bindingAttr)) memberInfos.Add(EnsureMemberWrapped(memberInfo)); return memberInfos.ToArray(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { List<MemberInfo> memberInfos = new List<MemberInfo>(); foreach (MemberInfo memberInfo in this.runtimeType.GetMembers(bindingAttr)) memberInfos.Add(EnsureMemberWrapped(memberInfo)); return memberInfos.ToArray(); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { Type nestedType = this.runtimeType.GetNestedType(name, bindingAttr); if (nestedType != null) nestedType = ResolveTypeFromTypeSystem(nestedType); return nestedType; } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { List<Type> nestedTypes = new List<Type>(); foreach (Type nestedType in this.runtimeType.GetNestedTypes(bindingAttr)) nestedTypes.Add(ResolveTypeFromTypeSystem(nestedType)); return nestedTypes.ToArray(); } public override Type GetInterface(string name, bool ignoreCase) { Type itfType = this.runtimeType.GetInterface(name, ignoreCase); if (itfType != null) itfType = ResolveTypeFromTypeSystem(itfType); return itfType; } public override Type[] GetInterfaces() { List<Type> itfTypes = new List<Type>(); foreach (Type itfType in this.runtimeType.GetInterfaces()) { Type interfaceType = ResolveTypeFromTypeSystem(itfType); itfTypes.Add(interfaceType); } return itfTypes.ToArray(); } public override object InvokeMember(string name, BindingFlags bindingFlags, Binder binder, object target, object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParams) { return this.runtimeType.InvokeMember(name, bindingFlags, binder, target, providedArgs, modifiers, culture, namedParams); } public override bool IsSubclassOf(Type potentialBaseType) { return System.Workflow.ComponentModel.Compiler.TypeProvider.IsSubclassOf(this.runtimeType, potentialBaseType); } public override bool IsAssignableFrom(Type c) { Type rtType = this.runtimeType; if (rtType.IsGenericTypeDefinition && this.IsGenericType) rtType = ResolveGenericTypeFromTypeSystem(rtType); return System.Workflow.ComponentModel.Compiler.TypeProvider.IsAssignable(rtType, c); } public override string ToString() { return this.runtimeType.ToString(); } public override int GetHashCode() { return this.runtimeType.GetHashCode(); } public override bool IsDefined(Type attributeType, bool inherit) { return this.runtimeType.IsDefined(attributeType, inherit); } public override Type GetElementType() { return ResolveTypeFromTypeSystem(this.runtimeType.GetElementType()); } #endregion #region Helpers private PropertyInfo EnsurePropertyWrapped(PropertyInfo realInfo) { PropertyInfo wrapperInfo = (PropertyInfo)this.memberMapping[realInfo]; if (wrapperInfo == null) { wrapperInfo = new RTPropertyInfoWrapper(this, realInfo); this.memberMapping.Add(realInfo, wrapperInfo); } return wrapperInfo; } internal MethodInfo EnsureMethodWrapped(MethodInfo realInfo) { MethodInfo wrapperInfo = (MethodInfo)this.memberMapping[realInfo]; if (wrapperInfo == null) { wrapperInfo = new RTMethodInfoWrapper(this, realInfo); this.memberMapping.Add(realInfo, wrapperInfo); } return wrapperInfo; } private MemberInfo EnsureMemberWrapped(MemberInfo memberInfo) { MemberInfo returnMemberInfo = null; if (memberInfo is PropertyInfo) returnMemberInfo = EnsurePropertyWrapped(memberInfo as PropertyInfo); else if (memberInfo is ConstructorInfo) returnMemberInfo = EnsureConstructorWrapped(memberInfo as ConstructorInfo); else if (memberInfo is EventInfo) returnMemberInfo = EnsureEventWrapped(memberInfo as EventInfo); else if (memberInfo is FieldInfo) returnMemberInfo = EnsureFieldWrapped(memberInfo as FieldInfo); else if (memberInfo is MethodInfo) returnMemberInfo = EnsureMethodWrapped(memberInfo as MethodInfo); return returnMemberInfo; } private ConstructorInfo EnsureConstructorWrapped(ConstructorInfo realInfo) { ConstructorInfo wrapperInfo = (ConstructorInfo)this.memberMapping[realInfo]; if (wrapperInfo == null) { wrapperInfo = new RTConstructorInfoWrapper(this, realInfo); this.memberMapping.Add(realInfo, wrapperInfo); } return wrapperInfo; } private EventInfo EnsureEventWrapped(EventInfo realInfo) { EventInfo wrapperInfo = (EventInfo)this.memberMapping[realInfo]; if (wrapperInfo == null) { wrapperInfo = new RTEventInfoWrapper(this, realInfo); this.memberMapping.Add(realInfo, wrapperInfo); } return wrapperInfo; } private FieldInfo EnsureFieldWrapped(FieldInfo realInfo) { FieldInfo wrapperInfo = (FieldInfo)this.memberMapping[realInfo]; if (wrapperInfo == null) { wrapperInfo = new RTFieldInfoWrapper(this, realInfo); this.memberMapping.Add(realInfo, wrapperInfo); } return wrapperInfo; } #endregion #region Support for generics public override bool IsGenericTypeDefinition { get { if (this.typeArgs != null && this.typeArgs.GetLength(0) > 0) return false; return this.runtimeType.IsGenericTypeDefinition; } } public override bool IsGenericParameter { get { return this.runtimeType.IsGenericParameter; } } public override int GenericParameterPosition { get { return this.runtimeType.GenericParameterPosition; } } public override bool IsGenericType { get { if (this.typeArgs != null && this.typeArgs.GetLength(0) > 0) return true; return this.runtimeType.IsGenericType; } } public override bool ContainsGenericParameters { get { if (this.typeArgs != null && this.typeArgs.GetLength(0) > 0) return false; return this.runtimeType.ContainsGenericParameters; } } public override Type[] GetGenericArguments() { return this.typeArgs; } public override Type GetGenericTypeDefinition() { if (this.IsGenericType) return this.runtimeType; return this; } public override Type MakeGenericType(params Type[] typeArgs) { if (typeArgs == null) throw new ArgumentNullException("typeArgs"); Type[] types = new Type[typeArgs.Length]; if (!IsGenericTypeDefinition) throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentValue), "typeArgs"); for (int i = 0; i < typeArgs.Length; i++) { types[i] = typeArgs[i]; if (types[i] == null) throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentValue), "typeArgs"); } Type returnType = this.boundedTypes[typeArgs] as Type; if (returnType == null) { // handle Nullable<T> specially if ((typeArgs.Length == 1) && (this.runtimeType == typeof(Nullable<>)) && !(typeArgs[0].IsEnum)) { switch (Type.GetTypeCode(typeArgs[0])) { case TypeCode.Boolean: returnType = typeof(bool?); break; case TypeCode.Byte: returnType = typeof(byte?); break; case TypeCode.Char: returnType = typeof(char?); break; case TypeCode.DateTime: returnType = typeof(DateTime?); break; case TypeCode.Decimal: returnType = typeof(decimal?); break; case TypeCode.Double: returnType = typeof(double?); break; case TypeCode.Int16: returnType = typeof(short?); break; case TypeCode.Int32: returnType = typeof(int?); break; case TypeCode.Int64: returnType = typeof(long?); break; case TypeCode.SByte: returnType = typeof(sbyte?); break; case TypeCode.Single: returnType = typeof(float?); break; case TypeCode.UInt16: returnType = typeof(ushort?); break; case TypeCode.UInt32: returnType = typeof(uint?); break; case TypeCode.UInt64: returnType = typeof(ulong?); break; default: // no special handling, so make it as usual returnType = new RTTypeWrapper(this.typeProvider, this.runtimeType, typeArgs); break; } } else { returnType = new RTTypeWrapper(this.typeProvider, this.runtimeType, typeArgs); } this.boundedTypes[typeArgs] = returnType; } return returnType; } public override Type MakeByRefType() { return this.typeProvider.GetType(this.FullName + "&"); } public override Type MakePointerType() { return this.typeProvider.GetType(this.FullName + "*"); } internal void OnAssemblyRemoved(Assembly removedAssembly) { ArrayList bindingArgs = new ArrayList(this.boundedTypes.Keys); foreach (Type[] types in bindingArgs) { foreach (Type type in types) { if (type.Assembly == removedAssembly) { this.boundedTypes.Remove(types); break; } } } } #endregion #region implementation overrides protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { foreach (ConstructorInfo ctorInfo in this.runtimeType.GetConstructors(bindingAttr)) { bool mismatch = false; if (types != null) { ParameterInfo[] parameters = ctorInfo.GetParameters(); if (parameters.GetLength(0) == types.Length) { for (int index = 0; !mismatch && index < parameters.Length; index++) mismatch = !IsAssignable(parameters[index].ParameterType, types[index]); } else { mismatch = true; } } if (!mismatch) return EnsureConstructorWrapped(ctorInfo); } return null; } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { foreach (MethodInfo method in this.runtimeType.GetMethods(bindingAttr)) { bool matchName = ((bindingAttr & BindingFlags.IgnoreCase) == BindingFlags.IgnoreCase) ? string.Compare(method.Name, name, StringComparison.OrdinalIgnoreCase) == 0 : string.Compare(method.Name, name, StringComparison.Ordinal) == 0; if (matchName) { bool mismatch = false; if (types != null) { ParameterInfo[] parameters = method.GetParameters(); if (parameters.GetLength(0) == types.Length) { for (int index = 0; !mismatch && index < parameters.Length; index++) mismatch = !IsAssignable(parameters[index].ParameterType, types[index]); } else { mismatch = true; } } if (!mismatch) return EnsureMethodWrapped(method); } } return null; } protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { foreach (PropertyInfo propInfo in this.runtimeType.GetProperties(bindingAttr)) { bool matchName = ((bindingAttr & BindingFlags.IgnoreCase) == BindingFlags.IgnoreCase) ? string.Compare(propInfo.Name, name, StringComparison.OrdinalIgnoreCase) == 0 : string.Compare(propInfo.Name, name, StringComparison.Ordinal) == 0; if (matchName && (returnType == null || (returnType.Equals(propInfo.PropertyType)))) { bool mismatch = false; if (types != null) { ParameterInfo[] parameters = propInfo.GetIndexParameters(); if (parameters.GetLength(0) == types.Length) { for (int index = 0; !mismatch && index < parameters.Length; index++) mismatch = !IsAssignable(parameters[index].ParameterType, types[index]); } else { mismatch = true; } } if (!mismatch) return EnsurePropertyWrapped(propInfo); } } return null; } protected override TypeAttributes GetAttributeFlagsImpl() { return this.runtimeType.Attributes; } protected override bool HasElementTypeImpl() { return this.runtimeType.HasElementType; } public override int GetArrayRank() { return this.runtimeType.GetArrayRank(); } protected override bool IsArrayImpl() { return this.runtimeType.IsArray; } protected override bool IsByRefImpl() { return this.runtimeType.IsByRef; } protected override bool IsCOMObjectImpl() { return this.runtimeType.IsCOMObject; } protected override bool IsContextfulImpl() { return this.runtimeType.IsContextful; } protected override bool IsMarshalByRefImpl() { return this.runtimeType.IsMarshalByRef; } protected override bool IsPointerImpl() { return this.runtimeType.IsPointer; } protected override bool IsPrimitiveImpl() { return this.runtimeType.IsPrimitive; } #endregion #region ICloneable Members public object Clone() { return this; } #endregion #region ConstructorInfo wrapper private class RTConstructorInfoWrapper : ConstructorInfo { private RTTypeWrapper rtTypeWrapper = null; private ConstructorInfo ctorInfo = null; private ParameterInfo[] wrappedParameters = null; public RTConstructorInfoWrapper(RTTypeWrapper rtTypeWrapper, ConstructorInfo ctorInfo) { this.rtTypeWrapper = rtTypeWrapper; this.ctorInfo = ctorInfo; } public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { return this.ctorInfo.Invoke(invokeAttr, binder, parameters, culture); } public override MethodAttributes Attributes { get { return this.ctorInfo.Attributes; } } public override MethodImplAttributes GetMethodImplementationFlags() { return this.ctorInfo.GetMethodImplementationFlags(); } public override ParameterInfo[] GetParameters() { if (this.wrappedParameters == null) { List<ParameterInfo> parameters = new List<ParameterInfo>(); foreach (ParameterInfo parameter in this.ctorInfo.GetParameters()) parameters.Add(new RTParameterInfoWrapper(this.rtTypeWrapper, this.ctorInfo, parameter)); this.wrappedParameters = parameters.ToArray(); } return this.wrappedParameters; } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { return this.ctorInfo.Invoke(obj, invokeAttr, binder, parameters, culture); } public override RuntimeMethodHandle MethodHandle { get { return this.ctorInfo.MethodHandle; } } public override Type DeclaringType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.ctorInfo.DeclaringType); } } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return this.ctorInfo.GetCustomAttributes(attributeType, inherit); } public override object[] GetCustomAttributes(bool inherit) { return this.ctorInfo.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return this.ctorInfo.IsDefined(attributeType, inherit); } public override MemberTypes MemberType { get { return this.ctorInfo.MemberType; } } public override string Name { get { return this.ctorInfo.Name; } } public override Type ReflectedType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.ctorInfo.ReflectedType); } } } #endregion #region FieldInfo Wrapper private class RTFieldInfoWrapper : FieldInfo { private RTTypeWrapper rtTypeWrapper = null; private FieldInfo fieldInfo = null; public RTFieldInfoWrapper(RTTypeWrapper rtTypeWrapper, FieldInfo fieldInfo) { this.rtTypeWrapper = rtTypeWrapper; this.fieldInfo = fieldInfo; } public override int MetadataToken { get { return this.fieldInfo.MetadataToken; } } public override Module Module { get { return this.fieldInfo.Module; } } public override FieldAttributes Attributes { get { return this.fieldInfo.Attributes; } } public override RuntimeFieldHandle FieldHandle { get { return this.fieldInfo.FieldHandle; } } public override Type FieldType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.fieldInfo.FieldType); } } public override object GetValue(object obj) { return this.fieldInfo.GetValue(obj); } public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { this.fieldInfo.SetValue(obj, value, invokeAttr, binder, culture); } public override Type DeclaringType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.fieldInfo.DeclaringType); } } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return this.fieldInfo.GetCustomAttributes(attributeType, inherit); } public override object[] GetCustomAttributes(bool inherit) { return this.fieldInfo.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return this.fieldInfo.IsDefined(attributeType, inherit); } public override MemberTypes MemberType { get { return this.fieldInfo.MemberType; } } public override string Name { get { return this.fieldInfo.Name; } } public override Type ReflectedType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.fieldInfo.ReflectedType); } } } #endregion #region PropertyInfo Wrapper private class RTPropertyInfoWrapper : PropertyInfo { private PropertyInfo propertyInfo = null; private RTTypeWrapper rtTypeWrapper = null; private ParameterInfo[] wrappedParameters = null; public RTPropertyInfoWrapper(RTTypeWrapper rtTypeWrapper, PropertyInfo propertyInfo) { this.rtTypeWrapper = rtTypeWrapper; this.propertyInfo = propertyInfo; } public override PropertyAttributes Attributes { get { return this.propertyInfo.Attributes; } } public override bool CanRead { get { return this.propertyInfo.CanRead; } } public override bool CanWrite { get { return this.propertyInfo.CanWrite; } } public override MethodInfo[] GetAccessors(bool nonPublic) { List<MethodInfo> methods = new List<MethodInfo>(); foreach (MethodInfo methodInfo in this.propertyInfo.GetAccessors(nonPublic)) methods.Add(this.rtTypeWrapper.EnsureMethodWrapped(methodInfo)); return methods.ToArray(); } public override MethodInfo GetGetMethod(bool nonPublic) { MethodInfo methodInfo = this.propertyInfo.GetGetMethod(nonPublic); if (methodInfo == null) return null; return this.rtTypeWrapper.EnsureMethodWrapped(methodInfo); } public override ParameterInfo[] GetIndexParameters() { if (this.wrappedParameters == null) { List<ParameterInfo> parameters = new List<ParameterInfo>(); foreach (ParameterInfo parameter in this.propertyInfo.GetIndexParameters()) parameters.Add(new RTParameterInfoWrapper(this.rtTypeWrapper, this.propertyInfo, parameter)); this.wrappedParameters = parameters.ToArray(); } return this.wrappedParameters; } public override MethodInfo GetSetMethod(bool nonPublic) { MethodInfo methodInfo = this.propertyInfo.GetSetMethod(nonPublic); if (methodInfo == null) return null; return this.rtTypeWrapper.EnsureMethodWrapped(methodInfo); } public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { return this.propertyInfo.GetValue(obj, invokeAttr, binder, index, culture); } public override Type PropertyType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.propertyInfo.PropertyType); } } public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { this.propertyInfo.SetValue(obj, value, invokeAttr, binder, index, culture); } public override Type DeclaringType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.propertyInfo.DeclaringType); } } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return this.propertyInfo.GetCustomAttributes(attributeType, inherit); } public override object[] GetCustomAttributes(bool inherit) { return this.propertyInfo.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return this.propertyInfo.IsDefined(attributeType, inherit); } public override MemberTypes MemberType { get { return this.propertyInfo.MemberType; } } public override string Name { get { return this.propertyInfo.Name; } } public override Type ReflectedType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.propertyInfo.ReflectedType); } } public override int MetadataToken { get { return this.propertyInfo.MetadataToken; } } public override Module Module { get { return this.propertyInfo.Module; } } } #endregion #region MethodInfo Wrapper private class RTMethodInfoWrapper : MethodInfo { private MethodInfo methodInfo = null; private RTTypeWrapper rtTypeWrapper = null; private ParameterInfo[] wrappedParameters = null; public RTMethodInfoWrapper(RTTypeWrapper rtTypeWrapper, MethodInfo methodInfo) { this.rtTypeWrapper = rtTypeWrapper; this.methodInfo = methodInfo; } public override Module Module { get { return this.methodInfo.Module; } } public override MethodBody GetMethodBody() { return this.methodInfo.GetMethodBody(); } public override int MetadataToken { get { return this.methodInfo.MetadataToken; } } public override CallingConventions CallingConvention { get { return this.methodInfo.CallingConvention; } } public override ParameterInfo ReturnParameter { get { return new RTParameterInfoWrapper(this.rtTypeWrapper, this, this.methodInfo.ReturnParameter); } } public override MethodInfo GetBaseDefinition() { return this.methodInfo.GetBaseDefinition(); } public override Type ReturnType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.methodInfo.ReturnType); } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return this.methodInfo.ReturnTypeCustomAttributes; } } public override MethodAttributes Attributes { get { return this.methodInfo.Attributes; } } public override MethodImplAttributes GetMethodImplementationFlags() { return this.methodInfo.GetMethodImplementationFlags(); } public override ParameterInfo[] GetParameters() { if (this.wrappedParameters == null) { List<ParameterInfo> parameters = new List<ParameterInfo>(); foreach (ParameterInfo parameter in this.methodInfo.GetParameters()) parameters.Add(new RTParameterInfoWrapper(this.rtTypeWrapper, this.methodInfo, parameter)); this.wrappedParameters = parameters.ToArray(); } return this.wrappedParameters; } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { return this.methodInfo.Invoke(obj, invokeAttr, binder, parameters, culture); } public override RuntimeMethodHandle MethodHandle { get { return this.methodInfo.MethodHandle; } } public override Type DeclaringType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.methodInfo.DeclaringType); } } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return this.methodInfo.GetCustomAttributes(attributeType, inherit); } public override object[] GetCustomAttributes(bool inherit) { return this.methodInfo.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return this.methodInfo.IsDefined(attributeType, inherit); } public override MemberTypes MemberType { get { return this.methodInfo.MemberType; } } public override string Name { get { return this.methodInfo.Name; } } public override Type ReflectedType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.methodInfo.ReflectedType); } } } #endregion #region EventInfo Wrapper private class RTEventInfoWrapper : EventInfo { private RTTypeWrapper rtTypeWrapper = null; private EventInfo eventInfo = null; public RTEventInfoWrapper(RTTypeWrapper rtTypeWrapper, EventInfo eventInfo) { this.rtTypeWrapper = rtTypeWrapper; this.eventInfo = eventInfo; } public override EventAttributes Attributes { get { return this.eventInfo.Attributes; } } public override MethodInfo GetAddMethod(bool nonPublic) { MethodInfo methodInfo = this.eventInfo.GetAddMethod(nonPublic); if (methodInfo == null) return null; return this.rtTypeWrapper.EnsureMethodWrapped(methodInfo); } public override MethodInfo GetRaiseMethod(bool nonPublic) { MethodInfo methodInfo = this.eventInfo.GetRaiseMethod(nonPublic); if (methodInfo == null) return null; return this.rtTypeWrapper.EnsureMethodWrapped(methodInfo); } public override MethodInfo GetRemoveMethod(bool nonPublic) { MethodInfo methodInfo = this.eventInfo.GetRemoveMethod(nonPublic); if (methodInfo == null) return null; return this.rtTypeWrapper.EnsureMethodWrapped(methodInfo); } public override Type DeclaringType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.eventInfo.DeclaringType); } } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return this.eventInfo.GetCustomAttributes(attributeType, inherit); } public override object[] GetCustomAttributes(bool inherit) { return this.eventInfo.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return this.eventInfo.IsDefined(attributeType, inherit); } public override MemberTypes MemberType { get { return this.eventInfo.MemberType; } } public override string Name { get { return this.eventInfo.Name; } } public override Type ReflectedType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.eventInfo.ReflectedType); } } public override int MetadataToken { get { return this.eventInfo.MetadataToken; } } public override Module Module { get { return this.eventInfo.Module; } } } #endregion #region ParameterInfo wrapper private class RTParameterInfoWrapper : ParameterInfo { private RTTypeWrapper rtTypeWrapper = null; private ParameterInfo paramInfo = null; private MemberInfo parentMember = null; public RTParameterInfoWrapper(RTTypeWrapper rtTypeWrapper, MemberInfo parentMember, ParameterInfo paramInfo) { this.parentMember = parentMember; this.rtTypeWrapper = rtTypeWrapper; this.paramInfo = paramInfo; } public override ParameterAttributes Attributes { get { return this.paramInfo.Attributes; } } public override object[] GetCustomAttributes(bool inherit) { return this.paramInfo.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return this.paramInfo.IsDefined(attributeType, inherit); } public override MemberInfo Member { get { return this.parentMember; } } public override Type[] GetOptionalCustomModifiers() { return this.paramInfo.GetOptionalCustomModifiers(); } public override string Name { get { return this.paramInfo.Name; } } public override Type ParameterType { get { return this.rtTypeWrapper.ResolveTypeFromTypeSystem(this.paramInfo.ParameterType); } } public override int Position { get { return this.paramInfo.Position; } } public override Type[] GetRequiredCustomModifiers() { return this.paramInfo.GetRequiredCustomModifiers(); } public override object DefaultValue { get { #pragma warning suppress 56503 throw new global::System.NotImplementedException(); } } } #endregion } }
namespace PeregrineDb.Tests.Databases { using System; using System.Diagnostics.CodeAnalysis; using FluentAssertions; using PeregrineDb.Dialects; using PeregrineDb.Tests.ExampleEntities; using PeregrineDb.Tests.Utils; using Xunit; public abstract partial class DefaultDatabaseConnectionCrudTests { public class DeleteId : DefaultDatabaseConnectionCrudTests { [Theory] [MemberData(nameof(TestDialects))] public void Deletes_the_entity_with_the_specified_id(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var id = database.Insert<int>(new Dog { Name = "Some name", Age = 10 }); // Act database.Delete<Dog>(id); // Assert database.Find<Dog>(id).Should().BeNull(); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_entity_with_string_key(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange database.Insert(new KeyString { Name = "Some Name", Age = 10 }); // Act database.Delete<KeyString>("Some Name"); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_entity_with_guid_key(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var id = Guid.NewGuid(); database.Insert(new KeyGuid { Id = id, Name = "Some Name" }); // Act database.Delete<KeyGuid>(id); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_entity_with_composite_keys(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var id = new { Key1 = 5, Key2 = 20 }; var entity = new CompositeKeys { Key1 = 5, Key2 = 20, Name = "Some Name" }; database.Insert(entity); // Act database.Delete<CompositeKeys>(id); } } } public class DeleteEntity : DefaultDatabaseConnectionCrudTests { [Theory] [MemberData(nameof(TestDialects))] public void Deletes_entity_with_matching_key(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var id = database.Insert<int>(new Dog { Name = "Some name", Age = 10 }); // Act var entity = database.Find<Dog>(id); database.Delete(entity); // Assert database.Find<Dog>(id).Should().BeNull(); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_entity_with_composite_keys(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange var id = new { Key1 = 5, Key2 = 20 }; var entity = new CompositeKeys { Key1 = 5, Key2 = 20, Name = "Some Name" }; database.Insert(entity); // Act database.Delete(entity); // Assert database.Find<CompositeKeys>(id).Should().BeNull(); } } } public class DeleteRange : DefaultDatabaseConnectionCrudTests { [Theory] [MemberData(nameof(TestDialectsWithData), new object[] { null })] [MemberData(nameof(TestDialectsWithData), "")] [MemberData(nameof(TestDialectsWithData), " ")] [MemberData(nameof(TestDialectsWithData), "HAVING Age = 10")] [MemberData(nameof(TestDialectsWithData), "WHERE")] public void Throws_exception_if_conditions_does_not_contain_where_clause(IDialect dialect, string conditions) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Act / Assert Assert.Throws<ArgumentException>(() => database.DeleteRange<Dog>(conditions)); } } [Theory] [MemberData(nameof(TestDialectsWithData), "Where Age = 10")] [MemberData(nameof(TestDialectsWithData), "where Age = 10")] [MemberData(nameof(TestDialectsWithData), "WHERE Age = 10")] [SuppressMessage("ReSharper", "AccessToDisposedClosure")] public void Allows_any_capitalization_of_where_clause(IDialect dialect, string conditions) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Act Action act = () => database.DeleteRange<Dog>(conditions); // Assert act.Should().NotThrow(); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_all_matching_entities(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange database.Insert(new Dog { Name = "Some Name 1", Age = 10 }); database.Insert(new Dog { Name = "Some Name 2", Age = 10 }); database.Insert(new Dog { Name = "Some Name 3", Age = 10 }); database.Insert(new Dog { Name = "Some Name 4", Age = 11 }); // Act var result = database.DeleteRange<Dog>($"WHERE Age = {10}"); // Assert result.NumRowsAffected.Should().Be(3); database.Count<Dog>().Should().Be(1); } } } public class DeleteRangeWhereObject : DefaultDatabaseConnectionCrudTests { [Theory] [MemberData(nameof(TestDialects))] public void Throws_exception_if_conditions_is_null(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Act / Assert Assert.Throws<ArgumentNullException>(() => database.DeleteRange<Dog>((object)null)); } } [Theory] [MemberData(nameof(TestDialects))] public void Throws_exception_if_conditions_is_empty(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Act / Assert Assert.Throws<ArgumentException>(() => database.DeleteRange<Dog>(new { })); } } [Theory] [MemberData(nameof(TestDialects))] public void Deletes_all_matching_entities(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange database.Insert(new Dog { Name = "Some Name 1", Age = 10 }); database.Insert(new Dog { Name = "Some Name 2", Age = 10 }); database.Insert(new Dog { Name = "Some Name 3", Age = 10 }); database.Insert(new Dog { Name = "Some Name 4", Age = 11 }); // Act var result = database.DeleteRange<Dog>(new { Age = 10 }); // Assert result.NumRowsAffected.Should().Be(3); database.Count<Dog>().Should().Be(1); } } } public class DeleteAll : DefaultDatabaseConnectionCrudTests { [Theory] [MemberData(nameof(TestDialects))] public void Deletes_all_entities(IDialect dialect) { using (var database = BlankDatabaseFactory.MakeDatabase(dialect)) { // Arrange database.Insert(new Dog { Name = "Some Name 1", Age = 10 }); database.Insert(new Dog { Name = "Some Name 2", Age = 10 }); database.Insert(new Dog { Name = "Some Name 3", Age = 10 }); database.Insert(new Dog { Name = "Some Name 4", Age = 11 }); // Act var result = database.DeleteAll<Dog>(); // Assert result.NumRowsAffected.Should().Be(4); database.Count<Dog>().Should().Be(0); } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using Knapcode.SocketToMe.Support; namespace Knapcode.SocketToMe.Socks { public class Socks5Client { private const byte SocksVersion = 0x05; private const byte UsernamePasswordVersion = 0x01; public Socket ConnectToServer(IPEndPoint endpoint) { return Tcp.ConnectToServer(endpoint, new[] { AddressFamily.InterNetwork, AddressFamily.InterNetworkV6 }); } public Socket ConnectToDestination(Socket socket, string name, int port, NetworkCredential credential = null, Encoding credentialEncoding = null) { ValidatePort(port, nameof(port)); byte[] nameBytes = Encoding.ASCII.GetBytes(name); byte[] addressBytes = Enumerable.Empty<byte>() .Concat(new[] {(byte) nameBytes.Length}) .Concat(nameBytes) .ToArray(); return Connect(socket, credential, credentialEncoding, AddressType.DomainName, addressBytes, port); } public Socket ConnectToDestination(Socket socket, IPEndPoint endpoint, NetworkCredential credential = null, Encoding credentialEncoding = null) { ValidatePort(endpoint.Port, nameof(endpoint)); AddressType addressType; byte[] addressBytes = endpoint.Address.GetAddressBytes(); switch (endpoint.AddressFamily) { case AddressFamily.InterNetwork: addressType = AddressType.IpV4; break; case AddressFamily.InterNetworkV6: addressType = AddressType.IpV6; break; default: throw new ArgumentException("The destination endpoint must be an IPv4 or IPv6 address."); } return Connect(socket, credential, credentialEncoding, addressType, addressBytes, endpoint.Port); } private Socket Connect(Socket socket, NetworkCredential credential, Encoding credentialEncoding, AddressType addressType, IEnumerable<byte> addressBytes, int port) { byte[] responseBuffer = Handshake(socket, credential, credentialEncoding); byte[] requestBuffer = Enumerable.Empty<byte>() .Concat(new[] {SocksVersion, (byte) CommandType.Connect, (byte) 0x00, (byte) addressType}) .Concat(addressBytes) .Concat(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short) port))) .ToArray(); socket.Send(requestBuffer); int read = socket.Receive(responseBuffer); if (read < 7) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with {0} bytes to the connect request. At least 7 bytes are expected.", read); throw new Exception(message); } ValidateSocksVersion(socket, responseBuffer[0]); if (responseBuffer[1] != (byte)ReplyType.Succeeded) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with a unsuccessful reply type '{0}' (0x{1:x2}).", responseBuffer[1] >= (byte) ReplyType.Unassigned ? ReplyType.Unassigned : (ReplyType) responseBuffer[1], responseBuffer[1]); throw new Exception(message); } if (responseBuffer[2] != 0x00) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with an unexpected reserved field value 0x{0:x2}. 0x00 was expected.", responseBuffer[2]); throw new Exception(message); } if (!Enum.GetValues(typeof (AddressType)).Cast<byte>().Contains(responseBuffer[3])) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with an unexpected address type 0x{0:x2}.", responseBuffer[3]); throw new Exception(message); } object bindAddress; object bindPort; var bindAddressType = (AddressType)responseBuffer[3]; switch (bindAddressType) { case AddressType.IpV4: if (read != 10) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with an unexpected number of bytes ({0} bytes) when the address is an IPv4 address. 10 bytes were expected.", read); throw new Exception(message); } bindAddress = new IPAddress(responseBuffer.Skip(4).Take(4).ToArray()); bindPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(responseBuffer, 8)); break; case AddressType.DomainName: byte bindAddressLength = responseBuffer[4]; bindAddress = Encoding.ASCII.GetString(responseBuffer, 5, bindAddressLength); bindPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(responseBuffer, 5 + bindAddressLength)); break; case AddressType.IpV6: if (read != 22) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with an unexpected number of bytes ({0} bytes) when the address is an IPv6 address. 22 bytes were expected.", read); throw new Exception(message); } bindAddress = new IPAddress(responseBuffer.Skip(4).Take(16).ToArray()); bindPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(responseBuffer, 20)); break; default: socket.Close(); string addressTypeNotImplementedMessage = string.Format( "The provided address type '{0}' is not yet implemented.", bindAddressType); throw new NotImplementedException(addressTypeNotImplementedMessage); } return socket; } private byte[] Handshake(Socket socket, NetworkCredential credential, Encoding credentialEncoding) { byte[] username = null; byte[] password = null; if (credential != null) { credentialEncoding = credentialEncoding ?? Encoding.UTF8; const string messageFormat = "The {0} in the provided credential encodes to {1} bytes. The maximum length is {2}."; username = credentialEncoding.GetBytes(credential.UserName); if (username.Length > byte.MaxValue) { string message = string.Format( CultureInfo.InvariantCulture, messageFormat, "username", username.Length, byte.MaxValue); throw new ArgumentException(message, nameof(credential)); } password = credentialEncoding.GetBytes(credential.Password); if (password.Length > byte.MaxValue) { string message = string.Format( CultureInfo.InvariantCulture, messageFormat, "password", password.Length, byte.MaxValue); throw new ArgumentException(message, nameof(credential)); } } // negotiate an authentication method var authenticationMethods = new List<AuthenticationMethod> { AuthenticationMethod.NoAuthentication }; if (username != null) { authenticationMethods.Add(AuthenticationMethod.UsernamePassword); } byte[] requestBuffer = Enumerable.Empty<byte>() .Concat(new[] { SocksVersion, (byte)authenticationMethods.Count }) .Concat(authenticationMethods.Select(m => (byte)m)) .ToArray(); socket.Send(requestBuffer); var responseBuffer = new byte[socket.ReceiveBufferSize]; int read = socket.Receive(responseBuffer, 0, 2, SocketFlags.None); if (read != 2) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with {0} bytes, instead of 2, during the handshake.", read); throw new Exception(message); } ValidateSocksVersion(socket, responseBuffer[0]); if (responseBuffer[1] == (byte)AuthenticationMethod.NoAcceptableMethods) { socket.Close(); throw new Exception("The SOCKS5 proxy does not support any of the client's authentication methods."); } if (authenticationMethods.All(m => responseBuffer[1] != (byte)m)) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with 0x{0:x2}, which is an unexpected authentication method.", responseBuffer[1]); throw new Exception(message); } // if username/password authentication was decided on, run the sub-negotiation if (responseBuffer[1] == (byte)AuthenticationMethod.UsernamePassword && username != null) { requestBuffer = Enumerable.Empty<byte>() .Concat(new[] { UsernamePasswordVersion, (byte)username.Length }) .Concat(username) .Concat(new[] { (byte)password.Length }) .Concat(password) .ToArray(); socket.Send(requestBuffer, SocketFlags.None); Console.WriteLine("SEND: {0}", BitConverter.ToString(requestBuffer)); read = socket.Receive(responseBuffer, 0, 2, SocketFlags.None); Console.WriteLine("RECEIVE: {0}", BitConverter.ToString(responseBuffer, 0, read)); if (read != 2) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with {0} bytes, instead of 2, during the username/password authentication.", read); throw new Exception(message); } if (responseBuffer[0] != UsernamePasswordVersion) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with 0x{0:x2}, instead of 0x{1:x2}, for the username/password authentication version number.", responseBuffer[0], UsernamePasswordVersion); throw new Exception(message); } if (responseBuffer[1] != 0) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with 0x{0:x2}, instead of 0x00, indicating a failure in username/password authentication.", responseBuffer[0]); throw new Exception(message); } } return responseBuffer; } private static void ValidateSocksVersion(Socket socket, byte version) { if (version != SocksVersion) { socket.Close(); string message = string.Format( "The SOCKS5 proxy responded with 0x{0:x2}, instead of 0x{1:x2}, for the SOCKS version number.", version, SocksVersion); throw new Exception(message); } } private static void ValidatePort(int port, string paramName) { if (port > ushort.MaxValue || port < 1) { string message = string.Format( "The port number {0} must be a positive number less than or equal to {1}.", port, ushort.MaxValue); throw new ArgumentException(message, paramName); } } private enum AddressType : byte { IpV4 = 0x01, DomainName = 0x03, IpV6 = 0x04 } private enum AuthenticationMethod : byte { NoAuthentication = 0x00, UsernamePassword = 0x02, NoAcceptableMethods = 0xFF } private enum CommandType : byte { Connect = 0x01 } private enum ReplyType : byte { Succeeded = 0x00, GeneralSocksServerFailure = 0x01, ConnectionNotAllowedByRuleset = 0x02, NetworkUnreachable = 0x03, HostUnreachable = 0x04, ConnectionRefused = 0x05, TtlExpired = 0x06, CommandNotSupport = 0x07, AddressTypeNotSupported = 0x08, Unassigned = 0x09 } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using MSCLoader; using UnityEngine; namespace RadioSubtitles { public class RadioSubtitles : Mod { private bool m_isLoaded; private AudioSource m_radioChannel1Source, m_radioFolkSource; private TextMesh m_subtitlesText; private string m_subtitlesFileOpen; private List<Subtitle> m_subtitles = new List<Subtitle>(); private GameObject m_player; private List<string> m_missing; private string m_lastSubtitles; public override string ID { get { return "RadioSubtitles"; } } public override string Name { get { return "RadioSubtitles"; } } public override string Author { get { return "zamp"; } } public override string Version { get { return "0.1.6"; } } public override bool UseAssetsFolder { get { return true; }} private class ChangeRadioClip : ConsoleCommand { private RadioSubtitles m_mod; public ChangeRadioClip(RadioSubtitles mod) { m_mod = mod; } public override string Help { get { return "Usage: changeradioclip clipname"; } } public override string Name { get { return "changeradioclip"; } } public override void Run(string[] args) { m_mod.PlayClip(args[0]); } } private class Subtitle { public float start, end; public string text; } //Called when mod is loading public override void OnLoad() { ConsoleCommand.Add(new ChangeRadioClip(this)); } // Update is called once per frame public override void Update() { try { if (Application.loadedLevelName == "GAME") { if (!m_isLoaded) { var path = Path.Combine(ModLoader.GetModAssetsFolder(this), "missing.txt"); m_missing = new List<string>(); if (File.Exists(path)) m_missing = File.ReadAllLines(path).ToList(); if (GameObject.Find("RadioChannels/Channel1") == null) return; if (GameObject.Find("GUI/Indicators/Subtitles") == null) return; if (GameObject.Find("PLAYER") == null) return; m_radioChannel1Source = GameObject.Find("RadioChannels/Channel1").GetComponent<AudioSource>(); m_radioFolkSource = GameObject.Find("RadioChannels/Folk").GetComponent<AudioSource>(); m_subtitlesText = GameObject.Find("GUI/Indicators/Subtitles").GetComponent<TextMesh>(); m_subtitlesText.richText = true; // enable rich text because why would you not have this enabled? m_player = GameObject.Find("PLAYER"); m_isLoaded = true; } } else if (Application.loadedLevelName != "GAME" && m_isLoaded) { m_isLoaded = false; m_radioChannel1Source = null; m_radioFolkSource = null; m_player = null; m_subtitlesText = null; } if (m_isLoaded) { UpdateRadioSubtitles(); } } catch (Exception e) { ModConsole.Error(e.ToString()); } } private void UpdateRadioSubtitles() { // only show subtitles when playing AudioSource source = null; if (m_radioChannel1Source.isPlaying && m_radioChannel1Source.volume > 0 && !m_radioChannel1Source.mute) { source = m_radioChannel1Source; } if (m_radioFolkSource.isPlaying && m_radioFolkSource.volume > 0 && !m_radioFolkSource.mute) { source = m_radioFolkSource; } if (source == null) { ClearSubtitles(); return; } var distance = Vector3.Distance(m_player.transform.position, source.transform.position); if (distance > (5 + source.volume * 10f)) { ClearSubtitles(); return; } // load subtitles var clip = source.clip.name; if (m_subtitlesFileOpen != clip) { var path = Path.Combine(ModLoader.GetModAssetsFolder(this), clip + ".encore.txt"); if (File.Exists(path)) { m_subtitlesFileOpen = clip; var lines = File.ReadAllLines(path); m_subtitles = new List<Subtitle>(); foreach (var line in lines) { var sub = new Subtitle(); var split = line.Split(' '); sub.start = ConvertTime(split[1]); sub.end = ConvertTime(split[2]); var str = ""; for (var i = 3; i < split.Length; ++i) { str += split[i] + " "; } sub.text = str; m_subtitles.Add(sub); } } else { if (!m_missing.Contains(clip) && source == m_radioChannel1Source) { m_missing.Add(clip); File.WriteAllLines(Path.Combine(ModLoader.GetModAssetsFolder(this), "missing.txt"), m_missing.ToArray()); } } } else { // correct subtitle is open // has to be at least 6 meters from radio to get subtitles if (m_subtitles.Any()) { var sub = m_subtitles[0]; if (source.time > sub.start && (m_subtitlesText.text == m_lastSubtitles || m_subtitlesText.text == "")) { m_subtitlesText.text = sub.text; m_lastSubtitles = sub.text; } if (source.time > sub.end) { ClearSubtitles(); m_subtitles.RemoveAt(0); } } } } private void ClearSubtitles() { if (m_subtitlesText.text == m_lastSubtitles) m_subtitlesText.text = ""; } private float ConvertTime(string time) { // convert 00:01:01:16 to seconds.decimals var bits = time.Split(':'); var seconds = (float)Convert.ToInt32(bits[0]) * 60 * 60; seconds += Convert.ToInt32(bits[1]) * 60; seconds += Convert.ToInt32(bits[2]); seconds += Convert.ToInt32(bits[3]) / 60f; return seconds; } internal void PlayClip(string clipname) { try { if (m_radioChannel1Source == null) return; var res = Resources.FindObjectsOfTypeAll<AudioClip>(); foreach (var audioClip in res) { if (audioClip != null && audioClip.name == clipname) { m_radioChannel1Source.clip = audioClip; m_radioChannel1Source.Play(); return; } } ModConsole.Print("no such clip"); } catch (Exception e) { ModConsole.Error(e.ToString()); } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Net; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Timers; using System.Web; using log4net; using log4net.Appender; using log4net.Core; using log4net.Repository; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Statistics; using Timer=System.Timers.Timer; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework.Servers { /// <summary> /// Common base for the main OpenSimServers (user, grid, inventory, region, etc) /// </summary> public abstract class BaseOpenSimServer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This will control a periodic log printout of the current 'show stats' (if they are active) for this /// server. /// </summary> private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000); protected CommandConsole m_console; protected OpenSimAppender m_consoleAppender; protected IAppender m_logFileAppender = null; /// <summary> /// Time at which this server was started /// </summary> protected DateTime m_startuptime; /// <summary> /// Record the initial startup directory for info purposes /// </summary> protected string m_startupDirectory = Environment.CurrentDirectory; protected string m_pidFile = String.Empty; /// <summary> /// Random uuid for private data /// </summary> protected string m_osSecret = String.Empty; protected BaseHttpServer m_httpServer; public BaseHttpServer HttpServer { get { return m_httpServer; } } /// <summary> /// Holds the non-viewer statistics collection object for this service/server /// </summary> protected IStatsCollector m_stats; public BaseOpenSimServer() { m_startuptime = DateTime.Now; // Random uuid for private data m_osSecret = UUID.Random().ToString(); m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics); m_periodicDiagnosticsTimer.Enabled = true; // Add ourselves to thread monitoring. This thread will go on to become the console listening thread Thread.CurrentThread.Name = "ConsoleThread"; ThreadTracker.Add(Thread.CurrentThread); ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "LogFileAppender") { m_logFileAppender = appender; } } System.Console.CancelKeyPress += new System.ConsoleCancelEventHandler(HandleConsoleCancelEvent); } protected void HandleConsoleCancelEvent(object sender, ConsoleCancelEventArgs args) { System.Console.Write("\nUse the SHUTDOWN command to exit this server cleanly.\nOr press the console close box to abort this server.\n" + m_console.DefaultPrompt + "# "); // Set the Cancel property to true to prevent the process from terminating. args.Cancel = true; } /// <summary> /// Must be overriden by child classes for their own server specific startup behaviour. /// </summary> protected virtual void StartupSpecific() { if (m_console != null) { ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "Console") { m_consoleAppender = (OpenSimAppender)appender; break; } } if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); } else { m_consoleAppender.Console = m_console; // If there is no threshold set then the threshold is effectively everything. if (null == m_consoleAppender.Threshold) m_consoleAppender.Threshold = Level.All; Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } m_console.Commands.AddCommand("base", false, "quit", "quit", "Quit the application", HandleQuit); m_console.Commands.AddCommand("base", false, "shutdown", "shutdown", "Quit the application", HandleQuit); m_console.Commands.AddCommand("base", false, "forcegc", "forcegc [ 0|1|2|*|now ]", "Forces an immediate full garbage collection (testing/dev only)", HandleForceGC); m_console.Commands.AddCommand("base", false, "set log level", "set log level <level>", "Set the console logging level", HandleLogLevel); m_console.Commands.AddCommand("base", false, "show info", "show info", "Show general information", HandleShow); m_console.Commands.AddCommand("base", false, "show stats", "show stats", "Show statistics", HandleShow); m_console.Commands.AddCommand("base", false, "show threads", "show threads", "Show thread status", HandleShow); m_console.Commands.AddCommand("base", false, "show uptime", "show uptime", "Show server uptime", HandleShow); m_console.Commands.AddCommand("base", false, "show version", "show version", "Show server version", HandleShow); } } /// <summary> /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing /// </summary> public virtual void ShutdownSpecific() {} /// <summary> /// Provides a list of help topics that are available. Overriding classes should append their topics to the /// information returned when the base method is called. /// </summary> /// /// <returns> /// A list of strings that represent different help topics on which more information is available /// </returns> protected virtual List<string> GetHelpTopics() { return new List<string>(); } /// <summary> /// Print statistics to the logfile, if they are active /// </summary> protected void LogDiagnostics(object source, ElapsedEventArgs e) { StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n"); sb.Append(GetUptimeReport()); if (m_stats != null) { sb.Append(m_stats.Report()); } sb.Append(Environment.NewLine); sb.Append(GetThreadsReport()); m_log.Debug(sb); } /// <summary> /// Get a report about the registered threads in this server. /// </summary> protected string GetThreadsReport() { StringBuilder sb = new StringBuilder(); List<Thread> threads = ThreadTracker.GetThreads(); if (threads == null) { sb.Append("Thread tracking is only enabled in DEBUG mode."); } else { sb.Append(threads.Count + " threads are being tracked:" + Environment.NewLine); foreach (Thread t in threads) { if (t.IsAlive) { sb.Append( "ID: " + t.ManagedThreadId + ", Name: " + t.Name + ", Alive: " + t.IsAlive + ", Pri: " + t.Priority + ", State: " + t.ThreadState + Environment.NewLine); } else { try { sb.Append("ID: " + t.ManagedThreadId + ", Name: " + t.Name + ", DEAD" + Environment.NewLine); } catch { sb.Append("THREAD ERROR" + Environment.NewLine); } } } } return sb.ToString(); } /// <summary> /// Return a report about the uptime of this server /// </summary> /// <returns></returns> protected string GetUptimeReport() { StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now)); sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime)); sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime)); return sb.ToString(); } /// <summary> /// Performs initialization of the scene, such as loading configuration from disk. /// </summary> public virtual void Startup() { m_log.Info("[STARTUP]: Beginning startup processing"); StartupSpecific(); // Report the version number near the end so you can still see it after startup. m_log.Info("[STARTUP]: Version: " + VersionInfo.Version + "\n"); TimeSpan timeTaken = DateTime.Now - m_startuptime; m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds); } /// <summary> /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing /// </summary> public virtual void Shutdown() { ShutdownSpecific(); m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting..."); RemovePIDFile(); Environment.Exit(0); } private void HandleQuit(string module, string[] args) { Shutdown(); } private void HandleForceGC(string module, string[] args) { // Default is an full (gen2) but NON-forced GC. int gen = 2; GCCollectionMode mode = GCCollectionMode.Optimized; if (args.Length > 1) { // Any argument implies forced GC. mode = GCCollectionMode.Forced; switch (args[1].ToLower()) { case "now": case "*": gen = GC.MaxGeneration; break; case "0": case "1": case "2": gen = Convert.ToInt32(args[1]); break; default: m_log.Warn("Usage: forcegc [ 0|1|2|*|now ]"); return; } } GC.Collect(gen, mode, true); } private void HandleLogLevel(string module, string[] cmd) { if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); return; } string rawLevel = cmd[3]; ILoggerRepository repository = LogManager.GetRepository(); Level consoleLevel = repository.LevelMap[rawLevel]; if (consoleLevel != null) m_consoleAppender.Threshold = consoleLevel; else Notice( String.Format( "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF", rawLevel)); Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } /// <summary> /// Show help information /// </summary> /// <param name="helpArgs"></param> protected virtual void ShowHelp(string[] helpArgs) { Notice(String.Empty); if (helpArgs.Length == 0) { Notice("set log level [level] - change the console logging level only. For example, off or debug."); Notice("show info - show server information (e.g. startup path)."); if (m_stats != null) Notice("show stats - show statistical information for this server"); Notice("show threads - list tracked threads"); Notice("show uptime - show server startup time and uptime."); Notice("show version - show server version."); Notice(String.Empty); return; } } public virtual void HandleShow(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "info": Notice("Version: " + VersionInfo.Version); Notice("Startup directory: " + m_startupDirectory); break; case "stats": if (m_stats != null) Notice(m_stats.Report()); break; case "threads": Notice(GetThreadsReport()); break; case "uptime": Notice(GetUptimeReport()); break; case "version": Notice( String.Format( "Version: {0}", VersionInfo.Version)); break; } } public virtual void HandleNuke(string module, string[] cmd) { } public virtual void HandleBlacklistOwner(string module, string[] cmd) { } public virtual void HandleBlacklistCreator(string module, string[] cmd) { } public virtual void HandleBlacklistName(string module, string[] cmd) { } public virtual void HandleBlacklistUser(string module, string[] cmd) { } public virtual void HandleBlacklistRemove(string module, string[] cmd) { } public virtual void HandleBlacklistClear(string module, string[] cmd) { } public virtual void HandleBlacklistShow(string module, string[] cmd) { } /// <summary> /// Console output is only possible if a console has been established. /// That is something that cannot be determined within this class. So /// all attempts to use the console MUST be verified. /// </summary> protected void Notice(string msg) { if (m_console != null) { m_console.Notice(msg); } } protected void CreatePIDFile(string path) { try { string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); FileStream fs = File.Create(path); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] buf = enc.GetBytes(pidstring); fs.Write(buf, 0, buf.Length); fs.Close(); m_pidFile = path; } catch (Exception) { } } public string osSecret { // Secret uuid for the simulator get { return m_osSecret; } } public string StatReport(OSHttpRequest httpRequest) { // If we catch a request for "callback", wrap the response in the value for jsonp if( httpRequest.QueryString["callback"] != null) { return httpRequest.QueryString["callback"] + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , VersionInfo.FullVersion ) + ");"; } else { return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , VersionInfo.FullVersion ); } } protected void RemovePIDFile() { if (!String.IsNullOrEmpty(m_pidFile)) { try { File.Delete(m_pidFile); m_pidFile = String.Empty; } catch (Exception) { } } } } }
using System; using System.Runtime.Serialization; namespace Codehaus.Parsec { /// <summary> ParserException is thrown when a grammar error happens. /// <p /> /// </summary> /// <author> Ben Yu /// /// 2004-11-12 /// </author> [Serializable] public class ParserException : System.SystemException { /// <summary> Get the parsing trace.</summary> /// <returns> the parsing trace /// with objects of {@link ParsingFrame} as the elements. /// </returns> public System.Collections.ArrayList getParsingTrace() { return frames; } /// <summary> Get the ParseError object.</summary> /// <returns> Returns the err. /// </returns> public ParseError getError() { return err; } /// <summary> Get the default formatted error message.</summary> /// <remarks> /// see java.lang.Throwable.getMessage. /// </remarks> public override string Message { get { return getErrorMessage(); } } private string getErrorMessage() { string msg = base.Message; System.Text.StringBuilder buf = new System.Text.StringBuilder(); if (msg != null) buf.Append(msg).Append("\n"); if (module != null) buf.Append(module).Append(" - "); buf.Append(DefaultShowError.Show(err, pos)); return buf.ToString(); } /// <summary> Gets the module name.</summary> /// <returns> the module name. /// </returns> virtual public string ModuleName { get { return module; } } /// <summary> Gets the line number of the error.</summary> /// <returns> the line number. /// </returns> virtual public int Line { get { return pos.Line; } } /// <summary> Gets the column number of the error.</summary> /// <returns> the column number. /// </returns> virtual public int Column { get { return pos.Column; } } private readonly ParseError err; private readonly Pos pos; private readonly string module; private System.Collections.ArrayList frames = new System.Collections.ArrayList(); internal virtual void pushFrame(ParsingFrame frame) { frames.Add(frame); } /// <summary> Print the resultion trace.</summary> /// <param name="writer">the output writer. /// </param> public void WriteParsingTrace(System.IO.TextWriter writer) { int size = frames.Count; for (int i = 0; i < size; i++) { writer.WriteLine(frames[i]); } writer.Flush(); } /// <summary> Prints the parsing trace to the standard error output.</summary> public void WriteParsingTrace() { using (System.IO.StreamWriter temp_writer = new System.IO.StreamWriter(System.Console.OpenStandardError(), System.Console.Error.Encoding)) { temp_writer.AutoFlush = true; WriteParsingTrace(temp_writer); } } public override string StackTrace { get { using (System.IO.StringWriter swriter = new System.IO.StringWriter()) { WriteParsingTrace(swriter); swriter.WriteLine(); return swriter.ToString() + base.StackTrace; } } } public ParserException() { } public ParserException(string msg) : base(msg) { } public ParserException(string msg, Exception innerException) : base(msg, innerException) { } /// <summary> Create a ParserException object.</summary> /// <param name="err">the ParseError object. /// </param> /// <param name="mname">the module name. /// </param> /// <param name="pos">the position. /// </param> public ParserException(ParseError err, string mname, Pos pos) { this.err = err; this.pos = pos; this.module = mname; } /// <summary> Create a ParserException object.</summary> /// <param name="message">the error message. /// </param> /// <param name="err">the ParseError object. /// </param> /// <param name="mname">the module name. /// </param> /// <param name="pos">the position. /// </param> public ParserException(string message, ParseError err, string mname, Pos pos) : base(message) { this.err = err; this.pos = pos; this.module = mname; } /// <param name="cause">the exception that causes this. /// </param> /// <param name="err">the ParseError object. /// </param> /// <param name="mname">the module name. /// </param> /// <param name="pos">the position. /// </param> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" public ParserException(System.Exception cause, ParseError err, string mname, Pos pos) : base(mname, cause) { this.err = err; this.pos = pos; this.module = mname; } /// <param name="message">the error message. /// </param> /// <param name="cause">the exception that causes this. /// </param> /// <param name="err">the ParseError object. /// </param> /// <param name="mname">the module name. /// </param> /// <param name="pos">the position. /// </param> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" public ParserException(string message, System.Exception cause, ParseError err, string mname, Pos pos) : base(message, cause) { this.err = err; this.pos = pos; this.module = mname; } protected ParserException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Orleans.CodeGeneration; using Orleans.Runtime.Configuration; using Orleans.Serialization; namespace Orleans.Runtime { internal class Message : IOutgoingMessage { // NOTE: These are encoded on the wire as bytes for efficiency. They are only integer enums to avoid boxing // This means we can't have over byte.MaxValue of them. public enum Header { ALWAYS_INTERLEAVE = 1, CACHE_INVALIDATION_HEADER, CATEGORY, CORRELATION_ID, DEBUG_CONTEXT, DIRECTION, EXPIRATION, FORWARD_COUNT, INTERFACE_ID, // DEPRECATED - leave that enum value to maintain next enum numerical values METHOD_ID, // DEPRECATED - leave that enum value to maintain next enum numerical values NEW_GRAIN_TYPE, GENERIC_GRAIN_TYPE, RESULT, REJECTION_INFO, REJECTION_TYPE, READ_ONLY, RESEND_COUNT, SENDING_ACTIVATION, SENDING_GRAIN, SENDING_SILO, IS_NEW_PLACEMENT, TARGET_ACTIVATION, TARGET_GRAIN, TARGET_SILO, TARGET_OBSERVER, TIMESTAMPS, // DEPRECATED - leave that enum value to maintain next enum numerical values IS_UNORDERED, PRIOR_MESSAGE_ID, PRIOR_MESSAGE_TIMES, REQUEST_CONTEXT, // Do not add over byte.MaxValue of these. } public static class Metadata { public const string MAX_RETRIES = "MaxRetries"; public const string EXCLUDE_TARGET_ACTIVATIONS = "#XA"; public const string TARGET_HISTORY = "TargetHistory"; public const string ACTIVATION_DATA = "ActivationData"; } public static int LargeMessageSizeThreshold { get; set; } public const int LENGTH_HEADER_SIZE = 8; public const int LENGTH_META_HEADER = 4; private readonly Dictionary<Header, object> headers; [NonSerialized] private Dictionary<string, object> metadata; /// <summary> /// NOTE: The contents of bodyBytes should never be modified /// </summary> private List<ArraySegment<byte>> bodyBytes; private List<ArraySegment<byte>> headerBytes; private object bodyObject; // Cache values of TargetAddess and SendingAddress as they are used very frequently private ActivationAddress targetAddress; private ActivationAddress sendingAddress; private static readonly TraceLogger logger; static Message() { logger = TraceLogger.GetLogger("Message", TraceLogger.LoggerType.Runtime); } public enum Categories { Ping, System, Application, } public enum Directions { Request, Response, OneWay } public enum ResponseTypes { Success, Error, Rejection } public enum RejectionTypes { Transient, Overloaded, DuplicateRequest, Unrecoverable, GatewayTooBusy, } public Categories Category { get { return GetScalarHeader<Categories>(Header.CATEGORY); } set { SetHeader(Header.CATEGORY, value); } } public Directions Direction { get { return GetScalarHeader<Directions>(Header.DIRECTION); } set { SetHeader(Header.DIRECTION, value); } } public bool IsReadOnly { get { return GetScalarHeader<bool>(Header.READ_ONLY); } set { SetHeader(Header.READ_ONLY, value); } } public bool IsAlwaysInterleave { get { return GetScalarHeader<bool>(Header.ALWAYS_INTERLEAVE); } set { SetHeader(Header.ALWAYS_INTERLEAVE, value); } } public bool IsUnordered { get { return GetScalarHeader<bool>(Header.IS_UNORDERED); } set { if (value || ContainsHeader(Header.IS_UNORDERED)) SetHeader(Header.IS_UNORDERED, value); } } public CorrelationId Id { get { return GetSimpleHeader<CorrelationId>(Header.CORRELATION_ID); } set { SetHeader(Header.CORRELATION_ID, value); } } public int ResendCount { get { return GetScalarHeader<int>(Header.RESEND_COUNT); } set { SetHeader(Header.RESEND_COUNT, value); } } public int ForwardCount { get { return GetScalarHeader<int>(Header.FORWARD_COUNT); } set { SetHeader(Header.FORWARD_COUNT, value); } } public SiloAddress TargetSilo { get { return (SiloAddress)GetHeader(Header.TARGET_SILO); } set { SetHeader(Header.TARGET_SILO, value); targetAddress = null; } } public GrainId TargetGrain { get { return GetSimpleHeader<GrainId>(Header.TARGET_GRAIN); } set { SetHeader(Header.TARGET_GRAIN, value); targetAddress = null; } } public ActivationId TargetActivation { get { return GetSimpleHeader<ActivationId>(Header.TARGET_ACTIVATION); } set { SetHeader(Header.TARGET_ACTIVATION, value); targetAddress = null; } } public ActivationAddress TargetAddress { get { return targetAddress ?? (targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation)); } set { TargetGrain = value.Grain; TargetActivation = value.Activation; TargetSilo = value.Silo; targetAddress = value; } } public GuidId TargetObserverId { get { return GetSimpleHeader<GuidId>(Header.TARGET_OBSERVER); } set { SetHeader(Header.TARGET_OBSERVER, value); targetAddress = null; } } public SiloAddress SendingSilo { get { return (SiloAddress)GetHeader(Header.SENDING_SILO); } set { SetHeader(Header.SENDING_SILO, value); sendingAddress = null; } } public GrainId SendingGrain { get { return GetSimpleHeader<GrainId>(Header.SENDING_GRAIN); } set { SetHeader(Header.SENDING_GRAIN, value); sendingAddress = null; } } public ActivationId SendingActivation { get { return GetSimpleHeader<ActivationId>(Header.SENDING_ACTIVATION); } set { SetHeader(Header.SENDING_ACTIVATION, value); sendingAddress = null; } } public ActivationAddress SendingAddress { get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); } set { SendingGrain = value.Grain; SendingActivation = value.Activation; SendingSilo = value.Silo; sendingAddress = value; } } public bool IsNewPlacement { get { return GetScalarHeader<bool>(Header.IS_NEW_PLACEMENT); } set { if (value || ContainsHeader(Header.IS_NEW_PLACEMENT)) SetHeader(Header.IS_NEW_PLACEMENT, value); } } public ResponseTypes Result { get { return GetScalarHeader<ResponseTypes>(Header.RESULT); } set { SetHeader(Header.RESULT, value); } } public DateTime Expiration { get { return GetScalarHeader<DateTime>(Header.EXPIRATION); } set { SetHeader(Header.EXPIRATION, value); } } public bool IsExpired { get { return (ContainsHeader(Header.EXPIRATION)) && DateTime.UtcNow > Expiration; } } public bool IsExpirableMessage(IMessagingConfiguration config) { if (!config.DropExpiredMessages) return false; GrainId id = TargetGrain; if (id == null) return false; // don't set expiration for one way, system target and system grain messages. return Direction != Directions.OneWay && !id.IsSystemTarget && !Constants.IsSystemGrain(id); } public string DebugContext { get { return GetStringHeader(Header.DEBUG_CONTEXT); } set { SetHeader(Header.DEBUG_CONTEXT, value); } } public IEnumerable<ActivationAddress> CacheInvalidationHeader { get { object obj = GetHeader(Header.CACHE_INVALIDATION_HEADER); return obj == null ? null : ((IEnumerable)obj).Cast<ActivationAddress>(); } } internal void AddToCacheInvalidationHeader(ActivationAddress address) { var list = new List<ActivationAddress>(); if (ContainsHeader(Header.CACHE_INVALIDATION_HEADER)) { var prevList = ((IEnumerable)GetHeader(Header.CACHE_INVALIDATION_HEADER)).Cast<ActivationAddress>(); list.AddRange(prevList); } list.Add(address); SetHeader(Header.CACHE_INVALIDATION_HEADER, list); } // Resends are used by the sender, usualy due to en error to send or due to a transient rejection. public bool MayResend(IMessagingConfiguration config) { return ResendCount < config.MaxResendCount; } // Forwardings are used by the receiver, usualy when it cannot process the message and forwars it to another silo to perform the processing // (got here due to outdated cache, silo is shutting down/overloaded, ...). public bool MayForward(GlobalConfiguration config) { return ForwardCount < config.MaxForwardCount; } /// <summary> /// Set by sender's placement logic when NewPlacementRequested is true /// so that receiver knows desired grain type /// </summary> public string NewGrainType { get { return GetStringHeader(Header.NEW_GRAIN_TYPE); } set { SetHeader(Header.NEW_GRAIN_TYPE, value); } } /// <summary> /// Set by caller's grain reference /// </summary> public string GenericGrainType { get { return GetStringHeader(Header.GENERIC_GRAIN_TYPE); } set { SetHeader(Header.GENERIC_GRAIN_TYPE, value); } } public RejectionTypes RejectionType { get { return GetScalarHeader<RejectionTypes>(Header.REJECTION_TYPE); } set { SetHeader(Header.REJECTION_TYPE, value); } } public string RejectionInfo { get { return GetStringHeader(Header.REJECTION_INFO); } set { SetHeader(Header.REJECTION_INFO, value); } } public Dictionary<string, object> RequestContextData { get { return GetScalarHeader<Dictionary<string, object>>(Header.REQUEST_CONTEXT); } set { SetHeader(Header.REQUEST_CONTEXT, value); } } public object BodyObject { get { if (bodyObject != null) { return bodyObject; } try { bodyObject = DeserializeBody(bodyBytes); } finally { if (bodyBytes != null) { BufferPool.GlobalPool.Release(bodyBytes); bodyBytes = null; } } return bodyObject; } set { bodyObject = value; if (bodyBytes == null) return; BufferPool.GlobalPool.Release(bodyBytes); bodyBytes = null; } } private static object DeserializeBody(List<ArraySegment<byte>> bytes) { if (bytes == null) { return null; } try { var stream = new BinaryTokenStreamReader(bytes); return SerializationManager.Deserialize(stream); } catch (Exception ex) { logger.Error(ErrorCode.Messaging_UnableToDeserializeBody, "Exception deserializing message body", ex); throw; } } public Message() { // average headers items count is 14 items, and while the Header enum contains 18 entries // the closest prime number is 17; assuming that possibility of all 18 headers being at the same time is low enough to // choose 17 in order to avoid allocations of two additional items on each call, and allocate 37 instead of 19 in rare cases headers = new Dictionary<Header, object>(17); metadata = new Dictionary<string, object>(); bodyObject = null; bodyBytes = null; headerBytes = null; } private Message(Categories type, Directions subtype) : this() { Category = type; Direction = subtype; } internal static Message CreateMessage(InvokeMethodRequest request, InvokeMethodOptions options) { var message = new Message( Categories.Application, (options & InvokeMethodOptions.OneWay) != 0 ? Directions.OneWay : Directions.Request) { Id = CorrelationId.GetNext(), IsReadOnly = (options & InvokeMethodOptions.ReadOnly) != 0, IsUnordered = (options & InvokeMethodOptions.Unordered) != 0, BodyObject = request }; if ((options & InvokeMethodOptions.AlwaysInterleave) != 0) message.IsAlwaysInterleave = true; var contextData = RequestContext.Export(); if (contextData != null) { message.RequestContextData = contextData; } return message; } // Initializes body and header but does not take ownership of byte. // Caller must clean up bytes public Message(List<ArraySegment<byte>> header, List<ArraySegment<byte>> body, bool deserializeBody = false) { metadata = new Dictionary<string, object>(); var input = new BinaryTokenStreamReader(header); headers = SerializationManager.DeserializeMessageHeaders(input); if (deserializeBody) { bodyObject = DeserializeBody(body); } else { bodyBytes = body; } } public Message CreateResponseMessage() { var response = new Message(this.Category, Directions.Response) { Id = this.Id, IsReadOnly = this.IsReadOnly, IsAlwaysInterleave = this.IsAlwaysInterleave, TargetSilo = this.SendingSilo }; if (this.ContainsHeader(Header.SENDING_GRAIN)) { response.SetHeader(Header.TARGET_GRAIN, this.GetHeader(Header.SENDING_GRAIN)); if (this.ContainsHeader(Header.SENDING_ACTIVATION)) { response.SetHeader(Header.TARGET_ACTIVATION, this.GetHeader(Header.SENDING_ACTIVATION)); } } response.SendingSilo = this.TargetSilo; if (this.ContainsHeader(Header.TARGET_GRAIN)) { response.SetHeader(Header.SENDING_GRAIN, this.GetHeader(Header.TARGET_GRAIN)); if (this.ContainsHeader(Header.TARGET_ACTIVATION)) { response.SetHeader(Header.SENDING_ACTIVATION, this.GetHeader(Header.TARGET_ACTIVATION)); } else if (this.TargetGrain.IsSystemTarget) { response.SetHeader(Header.SENDING_ACTIVATION, ActivationId.GetSystemActivation(TargetGrain, TargetSilo)); } } if (this.ContainsHeader(Header.DEBUG_CONTEXT)) { response.SetHeader(Header.DEBUG_CONTEXT, this.GetHeader(Header.DEBUG_CONTEXT)); } if (this.ContainsHeader(Header.CACHE_INVALIDATION_HEADER)) { response.SetHeader(Header.CACHE_INVALIDATION_HEADER, this.GetHeader(Header.CACHE_INVALIDATION_HEADER)); } if (this.ContainsHeader(Header.EXPIRATION)) { response.SetHeader(Header.EXPIRATION, this.GetHeader(Header.EXPIRATION)); } var contextData = RequestContext.Export(); if (contextData != null) { response.RequestContextData = contextData; } return response; } public Message CreateRejectionResponse(RejectionTypes type, string info, OrleansException ex = null) { var response = CreateResponseMessage(); response.Result = ResponseTypes.Rejection; response.RejectionType = type; response.RejectionInfo = info; response.BodyObject = ex; if (logger.IsVerbose) logger.Verbose("Creating {0} rejection with info '{1}' for {2} at:" + Environment.NewLine + "{3}", type, info, this, new System.Diagnostics.StackTrace(true)); return response; } public Message CreatePromptExceptionResponse(Exception exception) { return new Message(Category, Directions.Response) { Result = ResponseTypes.Error, BodyObject = Response.ExceptionResponse(exception) }; } public bool ContainsHeader(Header tag) { return headers.ContainsKey(tag); } public void RemoveHeader(Header tag) { lock (headers) { headers.Remove(tag); if (tag == Header.TARGET_ACTIVATION || tag == Header.TARGET_GRAIN | tag == Header.TARGET_SILO) targetAddress = null; } } public void SetHeader(Header tag, object value) { lock (headers) { headers[tag] = value; } } public object GetHeader(Header tag) { object val; bool flag; lock (headers) { flag = headers.TryGetValue(tag, out val); } return flag ? val : null; } public string GetStringHeader(Header tag) { object val; if (!headers.TryGetValue(tag, out val)) return String.Empty; var s = val as string; return s ?? String.Empty; } public T GetScalarHeader<T>(Header tag) { object val; if (headers.TryGetValue(tag, out val)) { return (T)val; } return default(T); } public T GetSimpleHeader<T>(Header tag) { object val; if (!headers.TryGetValue(tag, out val) || val == null) return default(T); return val is T ? (T) val : default(T); } public bool ContainsMetadata(string tag) { return metadata != null && metadata.ContainsKey(tag); } public void SetMetadata(string tag, object data) { metadata = metadata ?? new Dictionary<string, object>(); metadata[tag] = data; } public void RemoveMetadata(string tag) { if (metadata != null) { metadata.Remove(tag); } } public object GetMetadata(string tag) { object data; if (metadata != null && metadata.TryGetValue(tag, out data)) { return data; } return null; } /// <summary> /// Tell whether two messages are duplicates of one another /// </summary> /// <param name="other"></param> /// <returns></returns> public bool IsDuplicate(Message other) { return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id); } #region Serialization public List<ArraySegment<byte>> Serialize(out int headerLength) { int dummy; return Serialize_Impl(out headerLength, out dummy); } private List<ArraySegment<byte>> Serialize_Impl(out int headerLengthOut, out int bodyLengthOut) { var headerStream = new BinaryTokenStreamWriter(); lock (headers) // Guard against any attempts to modify message headers while we are serializing them { SerializationManager.SerializeMessageHeaders(headers, headerStream); } if (bodyBytes == null) { var bodyStream = new BinaryTokenStreamWriter(); SerializationManager.Serialize(bodyObject, bodyStream); // We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message // being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the // serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually // pretty high (an array allocation plus a bunch of copying). bodyBytes = bodyStream.ToBytes() as List<ArraySegment<byte>>; } if (headerBytes != null) { BufferPool.GlobalPool.Release(headerBytes); } headerBytes = headerStream.ToBytes() as List<ArraySegment<byte>>; int headerLength = headerBytes.Sum(ab => ab.Count); int bodyLength = bodyBytes.Sum(ab => ab.Count); var bytes = new List<ArraySegment<byte>>(); bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(headerLength))); bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(bodyLength))); bytes.AddRange(headerBytes); bytes.AddRange(bodyBytes); if (headerLength + bodyLength > LargeMessageSizeThreshold) { logger.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}", headerLength + bodyLength + LENGTH_HEADER_SIZE, headerLength, bodyLength, bytes.Count, this.ToString()); if (logger.IsVerbose3) logger.Verbose3("Sending large message {0}", this.ToLongString()); } headerLengthOut = headerLength; bodyLengthOut = bodyLength; return bytes; } public void ReleaseBodyAndHeaderBuffers() { ReleaseHeadersOnly(); ReleaseBodyOnly(); } public void ReleaseHeadersOnly() { if (headerBytes == null) return; BufferPool.GlobalPool.Release(headerBytes); headerBytes = null; } public void ReleaseBodyOnly() { if (bodyBytes == null) return; BufferPool.GlobalPool.Release(bodyBytes); bodyBytes = null; } #endregion // For testing and logging/tracing public string ToLongString() { var sb = new StringBuilder(); string debugContex = DebugContext; if (!string.IsNullOrEmpty(debugContex)) { // if DebugContex is present, print it first. sb.Append(debugContex).Append("."); } lock (headers) { foreach (var pair in headers) { if (pair.Key != Header.DEBUG_CONTEXT) { sb.AppendFormat("{0}={1};", pair.Key, pair.Value); } sb.AppendLine(); } } return sb.ToString(); } public override string ToString() { string response = String.Empty; if (Direction == Directions.Response) { switch (Result) { case ResponseTypes.Error: response = "Error "; break; case ResponseTypes.Rejection: response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo); break; default: break; } } return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}{9}: {10}", IsReadOnly ? "ReadOnly " : "", //0 IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1 IsNewPlacement ? "NewPlacement " : "", // 2 response, //3 Direction, //4 String.Format("{0}{1}{2}", SendingSilo, SendingGrain, SendingActivation), //5 String.Format("{0}{1}{2}{3}", TargetSilo, TargetGrain, TargetActivation, TargetObserverId), //6 Id, //7 ResendCount > 0 ? "[ResendCount=" + ResendCount + "]" : "", //8 ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "", //9 DebugContext); //10 } internal void SetTargetPlacement(PlacementResult value) { if ((value.IsNewPlacement || (ContainsHeader(Header.TARGET_ACTIVATION) && !TargetActivation.Equals(value.Activation)))) { RemoveHeader(Header.PRIOR_MESSAGE_ID); RemoveHeader(Header.PRIOR_MESSAGE_TIMES); } TargetActivation = value.Activation; TargetSilo = value.Silo; if (value.IsNewPlacement) IsNewPlacement = true; if (!String.IsNullOrEmpty(value.GrainType)) NewGrainType = value.GrainType; } public string GetTargetHistory() { var history = new StringBuilder(); history.Append("<"); if (ContainsHeader(Header.TARGET_SILO)) { history.Append(TargetSilo).Append(":"); } if (ContainsHeader(Header.TARGET_GRAIN)) { history.Append(TargetGrain).Append(":"); } if (ContainsHeader(Header.TARGET_ACTIVATION)) { history.Append(TargetActivation); } history.Append(">"); if (ContainsMetadata(Message.Metadata.TARGET_HISTORY)) { history.Append(" ").Append(GetMetadata(Message.Metadata.TARGET_HISTORY)); } return history.ToString(); } public bool IsSameDestination(IOutgoingMessage other) { var msg = (Message)other; return msg != null && Object.Equals(TargetSilo, msg.TargetSilo); } // For statistical measuring of time spent in queues. private ITimeInterval timeInterval; public void Start() { timeInterval = TimeIntervalFactory.CreateTimeInterval(true); timeInterval.Start(); } public void Stop() { timeInterval.Stop(); } public void Restart() { timeInterval.Restart(); } public TimeSpan Elapsed { get { return timeInterval.Elapsed; } } internal void DropExpiredMessage(MessagingStatisticsGroup.Phase phase) { MessagingStatisticsGroup.OnMessageExpired(phase); if (logger.IsVerbose2) logger.Verbose2("Dropping an expired message: {0}", this); ReleaseBodyAndHeaderBuffers(); } } }
// 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.Drawing; using System.Globalization; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using WebsitePanel.Providers.HeliconZoo; using WebsitePanel.Providers.ResultObjects; using WebsitePanel.Providers.Web; using WebsitePanel.Providers.WebAppGallery; using WebsitePanel.WebPortal; namespace WebsitePanel.Portal { public class ShortHeliconZooEngineComparer:IComparer<ShortHeliconZooEngine> { public int Compare(ShortHeliconZooEngine x, ShortHeliconZooEngine y) { return string.Compare(x.DisplayName, y.DisplayName, StringComparison.OrdinalIgnoreCase); } } public partial class WebSitesHeliconZooControl : WebsitePanelControlBase { protected void Page_Load(object sender, EventArgs e) { } public void BindWebItem(WebSite site) { ViewState["WebSiteId"] = site.SiteId; ViewState["WebSitePackageId"] = site.PackageId; try { BindEngines(site); BindInstalledApplications(); } catch (Exception ex) { lblConsole.Text = "Zoo Module is not installed. Please ask your system administrator to install Zoo on the server to Configuration\\Server\\Web Application Engines."; lblConsole.ForeColor = Color.Red; lblConsole.Font.Size = 16; return; // Exit } BindApplications(); } private void BindEngines(WebSite site) { // get allowed engines for current hosting plan ShortHeliconZooEngine[] allowedEngineArray = ES.Services.HeliconZoo.GetAllowedHeliconZooQuotasForPackage(site.PackageId); Array.Sort(allowedEngineArray, new ShortHeliconZooEngineComparer()); // get enabled engines for this site from applicationHost.config string[] enabledEngineNames = ES.Services.HeliconZoo.GetEnabledEnginesForSite(site.SiteId, site.PackageId); ViewState["EnabledEnginesNames"] = enabledEngineNames; //console allowed in applicationHost.config ViewState["IsZooWebConsoleEnabled"] = enabledEngineNames.Contains("console", StringComparer.OrdinalIgnoreCase); List<ShortHeliconZooEngine> allowedEngines = new List<ShortHeliconZooEngine>(allowedEngineArray); // fix engine name and check is web console enabled foreach (ShortHeliconZooEngine engine in allowedEngines) { engine.Name = engine.Name.Replace("HeliconZoo.", ""); //engine.Enabled = enabledEngineNames.Contains(engine.Name, StringComparer.OrdinalIgnoreCase); if (engine.Name == "console") { //console allowed in hosting plan ViewState["IsZooWebConsoleEnabled"] = engine.Enabled; } } ViewState["AllowedEngines"] = allowedEngines; } private void BindInstalledApplications() { ViewState["IsZooEnabled"] = false; var installedApplications = ES.Services.WebServers.GetZooApplications(PanelRequest.ItemID); ViewState["IsZooEnabled"] = true; if ((bool) ViewState["IsZooWebConsoleEnabled"]) { gvInstalledApplications.DataSource = installedApplications; gvInstalledApplications.DataBind(); } else { HideInstalledApplications(); } } private void HideInstalledApplications() { gvInstalledApplications.Visible = false; lblConsole.Visible = false; } private void BindApplications() { WebAppGalleryHelpers helper = new WebAppGalleryHelpers(); GalleryApplicationsResult result = helper.GetGalleryApplications("ZooTemplate", PanelSecurity.PackageId); List<GalleryApplication> applications = result.Value as List<GalleryApplication>; List<GalleryApplication> filteredApplications = new List<GalleryApplication>(); List<ShortHeliconZooEngine> allowedEngines = (List<ShortHeliconZooEngine>)ViewState["AllowedEngines"]; if (null != allowedEngines) { foreach (GalleryApplication application in applications) { foreach (string keyword in application.Keywords) { bool appAlreadyAdded = false; if (keyword.StartsWith("ZooEngine", StringComparison.OrdinalIgnoreCase)) { string appEngine = keyword.Substring("ZooEngine".Length); foreach (ShortHeliconZooEngine engine in allowedEngines) { if (!engine.Enabled) { continue; //skip } if ( string.Equals(appEngine, engine.KeywordedName, StringComparison.OrdinalIgnoreCase) || engine.Name == "*" ) { filteredApplications.Add(application); appAlreadyAdded = true; break; } } if (appAlreadyAdded) { break; } } } } } else { filteredApplications.AddRange(applications); } gvApplications.DataSource = filteredApplications; gvApplications.DataBind(); } public void SaveWebItem(WebSite site) { UpdatedAllowedEngines(); } protected void gvApplications_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Install") { UpdatedAllowedEngines(); Response.Redirect(GetWebAppInstallUrl(e.CommandArgument.ToString())); } } private void UpdatedAllowedEngines() { if (!(bool) ViewState["IsZooEnabled"]) { return; // exit; } List<ShortHeliconZooEngine> allowedEngines = (List<ShortHeliconZooEngine>)ViewState["AllowedEngines"]; string[] enabledEngineNames = (string[])ViewState["EnabledEnginesNames"]; // check that all allowed engines are enabled bool allAllowedAreEnabled = true; if (allowedEngines.Count != enabledEngineNames.Length) { allAllowedAreEnabled = false; } else { foreach (ShortHeliconZooEngine allowedEngine in allowedEngines) { if (!enabledEngineNames.Contains(allowedEngine.Name, StringComparer.OrdinalIgnoreCase)) { allAllowedAreEnabled = false; } } } if (!allAllowedAreEnabled) { List<string> updateEnabledEngineNames = new List<string>(); // by default allow for site all engines allowed by hosting plan foreach (ShortHeliconZooEngine heliconZooEngine in allowedEngines) { updateEnabledEngineNames.Add(heliconZooEngine.Name); } string siteId = ViewState["WebSiteId"] as string; int packageId = (int) ViewState["WebSitePackageId"]; ES.Services.HeliconZoo.SetEnabledEnginesForSite(siteId, packageId, updateEnabledEngineNames.ToArray()); } } protected void gvApplications_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvApplications.PageIndex = e.NewPageIndex; // categorized app list BindApplications(); } protected string GetIconUrlOrDefault(string url) { if (string.IsNullOrEmpty(url)) { return "/App_Themes/Default/icons/sphere_128.png"; } return "~/DesktopModules/WebsitePanel/ResizeImage.ashx?width=120&height=120&url=" + Server.UrlEncode(url); } protected string GetWebAppInstallUrl(string appId) { //http://localhost:9001/Default.aspx?pid=SpaceWebApplicationsGallery&mid=122&ctl=edit&ApplicationID=DotNetNuke&SpaceID=7 var mid = GetWebAppGaleryModuleId(); List<string> url = new List<string>(); url.Add("pid=SpaceWebApplicationsGallery"); url.Add(string.Format("{0}={1}", DefaultPage.MODULE_ID_PARAM, mid)); url.Add("ctl=edit"); url.Add("SpaceID="+PanelSecurity.PackageId.ToString(CultureInfo.InvariantCulture)); url.Add("ApplicationID=" + appId); string siteId = ViewState["WebSiteId"] as string; if (!string.IsNullOrEmpty(siteId)) { url.Add("SiteId="+siteId); } url.Add("ReturnUrl=" + Server.UrlEncode(Request.RawUrl)); return "~/Default.aspx?" + String.Join("&", url.ToArray()); } private static int GetWebAppGaleryModuleId() { // default value, valid in 2.1.0.166 int mid = 124; foreach (KeyValuePair<int, PageModule> pair in PortalConfiguration.Site.Modules) { if (string.Equals(pair.Value.ModuleDefinitionID, "webapplicationsgallery", StringComparison.OrdinalIgnoreCase)) { mid = pair.Value.ModuleId; break; } } return mid; } protected void gvInstalledApplications_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "EnableConsole") { UpdatedAllowedEngines(); string appName = e.CommandArgument.ToString(); ES.Services.WebServers.SetZooConsoleEnabled(PanelRequest.ItemID, appName); BindInstalledApplications(); } if (e.CommandName == "DisableConsole") { UpdatedAllowedEngines(); string appName = e.CommandArgument.ToString(); ES.Services.WebServers.SetZooConsoleDisabled(PanelRequest.ItemID, appName); BindInstalledApplications(); } } protected bool IsNullOrEmpty(string value) { return string.IsNullOrEmpty(value); } protected string GetConsoleFullUrl(string consoleUrl) { WebSite site = ES.Services.WebServers.GetWebSite(PanelRequest.ItemID); return "http://" + site.Name + consoleUrl; } } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ContainerRegistry { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// RegistriesOperations operations. /// </summary> public partial interface IRegistriesOperations { /// <summary> /// Checks whether the container registry name is available for use. /// The name must contain only alphanumeric characters, be globally /// unique, and between 5 and 60 characters in length. /// </summary> /// <param name='name'> /// The name of the container registry. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RegistryNameStatus>> CheckNameAvailabilityWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the properties of the specified container registry. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry /// belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Registry>> GetWithHttpMessagesAsync(string resourceGroupName, string registryName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a container registry with the specified parameters. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry /// belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='registryCreateParameters'> /// The parameters for creating a container registry. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Registry>> CreateWithHttpMessagesAsync(string resourceGroupName, string registryName, RegistryCreateParameters registryCreateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a container registry. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry /// belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string registryName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a container registry with the specified parameters. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry /// belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='registryUpdateParameters'> /// The parameters for updating a container registry. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Registry>> UpdateWithHttpMessagesAsync(string resourceGroupName, string registryName, RegistryUpdateParameters registryUpdateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the container registries under the specified resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry /// belongs. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Registry>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the container registries under the specified /// subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Registry>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the login credentials for the specified container registry. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry /// belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RegistryListCredentialsResult>> ListCredentialsWithHttpMessagesAsync(string resourceGroupName, string registryName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates one of the login credentials for the specified /// container registry. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry /// belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='name'> /// Specifies name of the password which should be regenerated -- /// password or password2. Possible values include: 'password', /// 'password2' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RegistryListCredentialsResult>> RegenerateCredentialWithHttpMessagesAsync(string resourceGroupName, string registryName, PasswordName name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a container registry with the specified parameters. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the container registry /// belongs. /// </param> /// <param name='registryName'> /// The name of the container registry. /// </param> /// <param name='registryCreateParameters'> /// The parameters for creating a container registry. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Registry>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string registryName, RegistryCreateParameters registryCreateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the container registries under the specified resource /// group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Registry>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the container registries under the specified /// subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Registry>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
#pragma warning disable using System.Collections.Generic; using XPT.Games.Generic.Entities; using XPT.Games.Generic.Maps; using XPT.Games.Yserbius; using XPT.Games.Yserbius.Entities; namespace XPT.Games.Yserbius.Maps { class YserMap33 : YsMap { public override int MapIndex => 33; protected override int RandomEncounterChance => 0; protected override int RandomEncounterExtraCount => 2; public YserMap33() { MapEvent01 = FnVOID_01; MapEvent02 = FnLIFE_02; MapEvent03 = FnTIMEA_03; MapEvent04 = FnTIMEB_04; MapEvent05 = FnTIMEC_05; MapEvent06 = FnTIMEELEM_06; MapEvent07 = FnTIMEPLAT_07; MapEvent08 = FnGOAL_08; MapEvent09 = FnENCA_09; MapEvent0A = FnENCB_0A; MapEvent0B = FnENCC_0B; MapEvent0C = FnENCD_0C; MapEvent0D = FnENCE_0D; MapEvent0E = FnENCF_0E; MapEvent0F = FnCROSSOVR_0F; MapEvent10 = FnMAPCONV_10; MapEvent12 = FnTELEBACK_12; } // === Strings ================================================ private const string String03FC = "The Ageless Void swallows you whole."; private const string String0421 = "Time freezes forever in your mind. To the rest of the world, you are dead."; private const string String046D = "You are dragged into the Waters of Death. Your death agonies are mercifully short."; private const string String04C0 = "The wall sparkles with phantasmal light."; private const string String04E9 = "A Timeswitch has been set."; private const string String0504 = "Two other Timeswitches must be set to reveal the platform."; private const string String053F = "The second Timeswitch has been set."; private const string String0563 = "The third and final Timeswitch has been set."; private const string String0590 = "All is deathly quiet near the Fountain of Life."; private const string String05C0 = "The wall sparkles with phantasmal light."; private const string String05E9 = "A Timeswitch has been set."; private const string String0604 = "Two other Timeswitches must be set to reveal the platform."; private const string String063F = "The second Timeswitch has been set."; private const string String0663 = "The third and final Timeswitch has been set."; private const string String0690 = "All is deathly quiet near the Fountain of Life."; private const string String06C0 = "The wall sparkles with phantasmal light."; private const string String06E9 = "A Timeswitch has been set."; private const string String0704 = "Two other Timeswitches must be set to reveal the platform."; private const string String073F = "The second Timeswitch has been set."; private const string String0763 = "The third and final Timeswitch has been set."; private const string String0790 = "All is deathly quiet near the Fountain of Life."; private const string String07C0 = "I am the Time Elemental, En-Li-Kil."; private const string String07E4 = "You have traveled far...only to die!"; private const string String0809 = "Your arrival frees me from my long imprisonment here -- halfway between two worlds."; private const string String085D = "I destroyed that fool Arnakkian Slowfoot, and I shall destroy you as easily."; private const string String08AA = "Then I shall search out all mortals in your world and destroy them!"; private const string String08EE = "I am En-Li-Kil! The immortal!!!"; private const string String090F = "You cross the Waters of Death safely."; private const string String0935 = "En-Li-Kil stands guard at the other side, protecting the Fountain of Life. This was the goal Arnakkian Slowfoot sought."; private const string String09AD = "You are dragged into the Waters of Death. Your death agonies are mercifully short."; private const string String0A00 = "You have found the Fountain of Life, but the waters are drained."; private const string String0A41 = "The Rainbow Gems and Golden Boat dissolve into dust."; private const string String0A76 = "Humiliating En-Li-Kil a second time is reward enough."; private const string String0AAC = "You stand on the Fountain of Life."; private const string String0ACF = "The Rainbow Gems and Golden Boat dissolve in the golden water."; private const string String0B0E = "You have defeated the Time Elemental En-Li-Kil."; private const string String0B3E = "You have won the game of life and death. You are now a HERO OF YSERBIUS."; private const string String0B88 = "Return to your home safely now."; private const string String0BA8 = "Soon you will be able to leave the volcano Yserbius and begin a new life of adventure!"; private const string String0BFF = "Farewell...this ending is just the beginning!!!"; private const string String0C2F = "Across the Waters of Death at the center of this finite square is the Fountain of Life."; private const string String0C87 = "The Fountain is well guarded."; private const string String0CA5 = "You leave this dimension and re-enter your world."; // === Functions ================================================ private void FnVOID_01(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String03FC); // The Ageless Void swallows you whole. ShowMessage(player, doMsgs, String0421); // Time freezes forever in your mind. To the rest of the world, you are dead. DamagePlayer(player, GetMaxHits(player)); } private void FnLIFE_02(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String046D); // You are dragged into the Waters of Death. Your death agonies are mercifully short. DamagePlayer(player, GetMaxHits(player)); } private void DoTimeSwitch(YsPlayerServer player, bool doMsgs, int switchIndex) { SetFlag(player, FlagTypeDungeon, YsIndexes.FlagKilledEnLiKilThisTime, 0); SetFlag(player, FlagTypeDungeon, switchIndex, 1); ShowMessage(player, doMsgs, String04C0); // The wall sparkles with phantasmal light. int setSwitchCount = player.MapData.GetFlag(FlagTypeDungeon, YsIndexes.FlagUnknownSwitch1) + player.MapData.GetFlag(FlagTypeDungeon, YsIndexes.FlagUnknownSwitch2) + player.MapData.GetFlag(FlagTypeDungeon, YsIndexes.FlagUnknownSwitch3); if (setSwitchCount == 1) { ShowMessage(player, doMsgs, String04E9); // A Timeswitch has been set. ShowMessage(player, doMsgs, String0504); // Two other Timeswitches must be set to reveal the platform. } else if (setSwitchCount == 2) { ShowMessage(player, doMsgs, String053F); // The second Timeswitch has been set. } else if (setSwitchCount == 3) { ShowMessage(player, doMsgs, String0563); // The third and final Timeswitch has been set. } else { ShowMessage(player, doMsgs, String0590); // All is deathly quiet near the Fountain of Life. } } private void FnTIMEA_03(YsPlayerServer player, MapEventType type, bool doMsgs) { DoTimeSwitch(player, doMsgs, YsIndexes.FlagUnknownSwitch1); } private void FnTIMEB_04(YsPlayerServer player, MapEventType type, bool doMsgs) { DoTimeSwitch(player, doMsgs, YsIndexes.FlagUnknownSwitch2); } private void FnTIMEC_05(YsPlayerServer player, MapEventType type, bool doMsgs) { DoTimeSwitch(player, doMsgs, YsIndexes.FlagUnknownSwitch3); } private void FnTIMEELEM_06(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, 0x0011); ShowMessage(player, doMsgs, String07C0); // I am the Time Elemental, En-Li-Kil. ShowMessage(player, doMsgs, String07E4); // You have traveled far...only to die! ShowMessage(player, doMsgs, String0809); // Your arrival frees me from my long imprisonment here -- halfway between two worlds. ShowMessage(player, doMsgs, String085D); // I destroyed that fool Arnakkian Slowfoot, and I shall destroy you as easily. ShowMessage(player, doMsgs, String08AA); // Then I shall search out all mortals in your world and destroy them! ShowMessage(player, doMsgs, String08EE); // I am En-Li-Kil! The immortal!!! SetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch1, 0x00); SetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch2, 0x00); SetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch3, 0x00); AddEncounter(player, 0x01, 0x21); AddEncounter(player, 0x02, 0x23); AddEncounter(player, 0x03, 0x10); AddEncounter(player, 0x04, 0x19); AddEncounter(player, 0x06, 0x28); } private void FnTIMEPLAT_07(YsPlayerServer player, MapEventType type, bool doMsgs) { // the water tile between the final platform and en-li-kil. int countSwitchesSet = GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch1) + GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch2) + GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch3); if (countSwitchesSet == 3 || (IsFlagOn(player, FlagTypeMap, 1) == 1)) { SetFloorItem(player, 0x00, 0xA8); ShowMessage(player, doMsgs, String090F); // You cross the Waters of Death safely. ShowMessage(player, doMsgs, String0935); // En-Li-Kil stands guard at the other side, protecting the Fountain of Life. This was the goal Arnakkian Slowfoot sought. ShowPortrait(player, 0x0042); } else { SetFloorItem(player, 0x03, 0xA8); ShowMessage(player, doMsgs, String09AD); // You are dragged into the Waters of Death. Your death agonies are mercifully short. DamagePlayer(player, GetMaxHits(player)); } } private void FnGOAL_08(YsPlayerServer player, MapEventType type, bool doMsgs) { RemoveItem(player, YsIndexes.ItemRanbowGemRed); RemoveItem(player, YsIndexes.ItemRanbowGemYellow); RemoveItem(player, YsIndexes.ItemRanbowGemGreen); RemoveItem(player, YsIndexes.ItemRanbowGemBlue); RemoveItem(player, YsIndexes.ItemGoldenBoat); if (GetFlag(player, FlagTypeDungeon, YsIndexes.FlagKilledEnLiKilThisTime) == 1) { ShowMessage(player, doMsgs, "You stand amidst the Waters of Death, surrounded on all sides by the Ageless Void. All is peace here."); return; } SetFlag(player, FlagTypeDungeon, YsIndexes.FlagKilledEnLiKilThisTime, 1); if (IsFlagOn(player, FlagTypeDungeon, YsIndexes.FlagDefeatedEnLiKil) == 1) { ShowMessage(player, doMsgs, String0A00); // You have found the Fountain of Life, but the waters are drained. ShowMessage(player, doMsgs, String0A41); // The Rainbow Gems and Golden Boat dissolve into dust. ShowMessage(player, doMsgs, String0A76); // Humiliating En-Li-Kil a second time is reward enough. return; } ShowMessage(player, doMsgs, String0AAC); // You stand on the Fountain of Life. ShowMessage(player, doMsgs, String0ACF); // The Rainbow Gems and Golden Boat dissolve in the golden water. ShowMessage(player, doMsgs, String0B0E); // You have defeated the Time Elemental En-Li-Kil. ShowMessage(player, doMsgs, String0B3E); // You have won the game of life and death. You are now a HERO OF YSERBIUS. ShowMessage(player, doMsgs, String0B88); // Return to your home safely now. ShowMessage(player, doMsgs, String0BA8); // Soon you will be able to leave the volcano Yserbius and begin a new life of adventure! ShowMessage(player, doMsgs, String0BFF); // Farewell...this ending is just the beginning!!! if (GetFlag(player, FlagTypeDungeon, YsIndexes.FlagReceivedEnLiKilExperience) == 0) { SetFlag(player, FlagTypeDungeon, YsIndexes.FlagReceivedEnLiKilExperience, 0x01); SetFlag(player, FlagTypeDungeon, YsIndexes.FlagDefeatedEnLiKil, 0x01); AddExperience(player, 0x004C4B40); } } private void FnENCA_09(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0C2F); // Across the Waters of Death at the center of this finite square is the Fountain of Life. ShowMessage(player, doMsgs, String0C87); // The Fountain is well guarded. AddEncounter(player, 0x01, 0x19); AddEncounter(player, 0x02, 0x1B); AddEncounter(player, 0x03, 0x19); AddEncounter(player, 0x04, 0x1B); AddEncounter(player, 0x05, 0x23); AddEncounter(player, 0x06, 0x1D); } private void FnENCB_0A(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x08); AddEncounter(player, 0x02, 0x08); AddEncounter(player, 0x03, 0x24); AddEncounter(player, 0x04, 0x25); AddEncounter(player, 0x05, 0x26); AddEncounter(player, 0x06, 0x27); } private void FnENCC_0B(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x1B); AddEncounter(player, 0x02, 0x1B); AddEncounter(player, 0x03, 0x1C); AddEncounter(player, 0x04, 0x1C); AddEncounter(player, 0x05, 0x1F); AddEncounter(player, 0x06, 0x1F); } private void FnENCD_0C(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x19); AddEncounter(player, 0x02, 0x19); AddEncounter(player, 0x03, 0x1C); AddEncounter(player, 0x04, 0x1C); AddEncounter(player, 0x05, 0x1D); AddEncounter(player, 0x06, 0x1D); } private void FnENCE_0D(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x1E); AddEncounter(player, 0x02, 0x1E); AddEncounter(player, 0x03, 0x20); AddEncounter(player, 0x04, 0x20); AddEncounter(player, 0x05, 0x18); AddEncounter(player, 0x06, 0x21); } private void FnENCF_0E(YsPlayerServer player, MapEventType type, bool doMsgs) { AddEncounter(player, 0x01, 0x22); AddEncounter(player, 0x02, 0x22); AddEncounter(player, 0x03, 0x1F); AddEncounter(player, 0x04, 0x1F); AddEncounter(player, 0x05, 0x23); AddEncounter(player, 0x06, 0x23); } private void FnCROSSOVR_0F(YsPlayerServer player, MapEventType type, bool doMsgs) { // the final platform, standing next to the bridged water tile to en-li-kil. int countSwitchesSet = GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch1) + GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch2) + GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch3); if (countSwitchesSet == 3) { SetFloorItem(player, 0x00, 0xA8); SetFlag(player, FlagTypeMap, 1, 1); // set a map flag allowing party members to not die even if they did not set the switches. } else { SetFloorItem(player, 0x03, 0xA8); } } private void FnMAPCONV_10(YsPlayerServer player, MapEventType type, bool doMsgs) { // beginning of the final platform, walking to the bridge to en-li-kil. int countSwitchesSet = GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch1) + GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch2) + GetFlag(player, FlagTypeDungeon, YsIndexes.FlagUnknownSwitch3); if (countSwitchesSet == 3 || (IsFlagOn(player, FlagTypeMap, 1) == 1)) { SetFloorItem(player, 0x00, 0xA8); } else { SetFloorItem(player, 0x03, 0xA8); } } private void FnTELEBACK_12(YsPlayerServer player, MapEventType type, bool doMsgs) { ShowMessage(player, doMsgs, String0CA5); // You leave this dimension and re-enter your world. TeleportParty(player, 0x38, 0x04, 0x88, 0x02, type); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; using ConsoleExamples.Examples; using Encog.MathUtil; using Encog.ML.Data.Specific; using Encog.Neural.BAM; using Encog.Neural.Networks; using Encog.Neural.Pattern; namespace Encog.Examples.BAM { /** * Simple class to recognize some patterns with a Bidirectional * Associative Memory (BAM) Neural Network. * This is very loosely based on a an example by Karsten Kutza, * written in C on 1996-01-24. * http://www.neural-networks-at-your-fingertips.com/bam.html * * I translated it to Java and adapted it to use Encog for neural * network processing. I mainly kept the patterns from the * original example. * */ public class BidirectionalAssociativeMemory : IExample { public const int IN_CHARS = 5; public const int OUT_CHARS = 7; public const int BITS_PER_CHAR = 6; public const char FIRST_CHAR = ' '; public const int INPUT_NEURONS = (IN_CHARS*BITS_PER_CHAR); public const int OUTPUT_NEURONS = (OUT_CHARS*BITS_PER_CHAR); public String[] NAMES = {"TINA ", "ANTJE", "LISA "}; public String[] NAMES2 = {"TINE ", "ANNJE", "RITA "}; public String[] PHONES = {"6843726", "8034673", "7260915"}; private IExampleInterface app; public static ExampleInfo Info { get { var info = new ExampleInfo( typeof (BidirectionalAssociativeMemory), "bam", "Bidirectional Associative Memory", "Uses a BAM to associate patterns in a bidirectional way."); return info; } } #region IExample Members public void Execute(IExampleInterface app) { this.app = app; var pattern = new BAMPattern(); pattern.F1Neurons = INPUT_NEURONS; pattern.F2Neurons = OUTPUT_NEURONS; var network = (BAMNetwork) pattern.Generate(); // train for (int i = 0; i < NAMES.Length; i++) { network.AddPattern( StringToBipolar(NAMES[i]), StringToBipolar(PHONES[i])); } // test for (int i = 0; i < NAMES.Length; i++) { var data = new NeuralDataMapping( StringToBipolar(NAMES[i]), RandomBiPolar(OUT_CHARS*BITS_PER_CHAR)); RunBAM(network, data); } app.WriteLine(); for (int i = 0; i < PHONES.Length; i++) { var data = new NeuralDataMapping( StringToBipolar(PHONES[i]), RandomBiPolar(IN_CHARS*BITS_PER_CHAR)); RunBAM(network, data); } app.WriteLine(); for (int i = 0; i < NAMES.Length; i++) { var data = new NeuralDataMapping( StringToBipolar(NAMES2[i]), RandomBiPolar(OUT_CHARS*BITS_PER_CHAR)); RunBAM(network, data); } } #endregion public BiPolarMLData StringToBipolar(String str) { var result = new BiPolarMLData(str.Length*BITS_PER_CHAR); int currentIndex = 0; for (int i = 0; i < str.Length; i++) { char ch = char.ToUpper(str[i]); int idx = ch - FIRST_CHAR; int place = 1; for (int j = 0; j < BITS_PER_CHAR; j++) { bool value = (idx & place) > 0; result.SetBoolean(currentIndex++, value); place *= 2; } } return result; } public String BipolalToString(BiPolarMLData data) { var result = new StringBuilder(); int j, a, p; for (int i = 0; i < (data.Count/BITS_PER_CHAR); i++) { a = 0; p = 1; for (j = 0; j < BITS_PER_CHAR; j++) { if (data.GetBoolean(i*BITS_PER_CHAR + j)) a += p; p *= 2; } result.Append((char) (a + FIRST_CHAR)); } return result.ToString(); } public BiPolarMLData RandomBiPolar(int size) { var result = new BiPolarMLData(size); for (int i = 0; i < size; i++) { if (ThreadSafeRandom.NextDouble() > 0.5) result[i] = -1; else result[i] = 1; } return result; } public String MappingToString(NeuralDataMapping mapping) { var result = new StringBuilder(); result.Append(BipolalToString((BiPolarMLData) mapping.From)); result.Append(" -> "); result.Append(BipolalToString((BiPolarMLData) mapping.To)); return result.ToString(); } public void RunBAM(BAMNetwork network, NeuralDataMapping data) { var line = new StringBuilder(); line.Append(MappingToString(data)); network.Compute(data); line.Append(" | "); line.Append(MappingToString(data)); app.WriteLine(line.ToString()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The RegexReplacement class represents a substitution string for // use when using regexs to search/replace, etc. It's logically // a sequence intermixed (1) constant strings and (2) group numbers. using System.Collections; using System.Collections.Generic; namespace System.Text.RegularExpressions { internal sealed class RegexReplacement { /* * Since RegexReplacement shares the same parser as Regex, * the constructor takes a RegexNode which is a concatenation * of constant strings and backreferences. */ internal RegexReplacement(String rep, RegexNode concat, Dictionary<Int32, Int32> _caps) { StringBuilder sb; List<String> strings; List<Int32> rules; int slot; _rep = rep; if (concat.Type() != RegexNode.Concatenate) throw new ArgumentException(SR.ReplacementError); sb = new StringBuilder(); strings = new List<String>(); rules = new List<Int32>(); for (int i = 0; i < concat.ChildCount(); i++) { RegexNode child = concat.Child(i); switch (child.Type()) { case RegexNode.Multi: sb.Append(child._str); break; case RegexNode.One: sb.Append(child._ch); break; case RegexNode.Ref: if (sb.Length > 0) { rules.Add(strings.Count); strings.Add(sb.ToString()); sb.Length = 0; } slot = child._m; if (_caps != null && slot >= 0) slot = (int)_caps[slot]; rules.Add(-Specials - 1 - slot); break; default: throw new ArgumentException(SR.ReplacementError); } } if (sb.Length > 0) { rules.Add(strings.Count); strings.Add(sb.ToString()); } _strings = strings; _rules = rules; } internal String _rep; internal List<String> _strings; // table of string constants internal List<Int32> _rules; // negative -> group #, positive -> string # // constants for special insertion patterns internal const int Specials = 4; internal const int LeftPortion = -1; internal const int RightPortion = -2; internal const int LastGroup = -3; internal const int WholeString = -4; /* * Given a Match, emits into the StringBuilder the evaluated * substitution pattern. */ private void ReplacementImpl(StringBuilder sb, Match match) { for (int i = 0; i < _rules.Count; i++) { int r = _rules[i]; if (r >= 0) // string lookup sb.Append(_strings[r]); else if (r < -Specials) // group lookup sb.Append(match.GroupToStringImpl(-Specials - 1 - r)); else { switch (-Specials - 1 - r) { // special insertion patterns case LeftPortion: sb.Append(match.GetLeftSubstring()); break; case RightPortion: sb.Append(match.GetRightSubstring()); break; case LastGroup: sb.Append(match.LastGroupToStringImpl()); break; case WholeString: sb.Append(match.GetOriginalString()); break; } } } } /* * Given a Match, emits into the List<String> the evaluated * Right-to-Left substitution pattern. */ private void ReplacementImplRTL(List<String> al, Match match) { for (int i = _rules.Count - 1; i >= 0; i--) { int r = _rules[i]; if (r >= 0) // string lookup al.Add(_strings[r]); else if (r < -Specials) // group lookup al.Add(match.GroupToStringImpl(-Specials - 1 - r)); else { switch (-Specials - 1 - r) { // special insertion patterns case LeftPortion: al.Add(match.GetLeftSubstring()); break; case RightPortion: al.Add(match.GetRightSubstring()); break; case LastGroup: al.Add(match.LastGroupToStringImpl()); break; case WholeString: al.Add(match.GetOriginalString()); break; } } } } /* * The original pattern string */ internal String Pattern { get { return _rep; } } /* * Returns the replacement result for a single match */ internal String Replacement(Match match) { StringBuilder sb = new StringBuilder(); ReplacementImpl(sb, match); return sb.ToString(); } /* * Three very similar algorithms appear below: replace (pattern), * replace (evaluator), and split. */ /* * Replaces all ocurrances of the regex in the string with the * replacement pattern. * * Note that the special case of no matches is handled on its own: * with no matches, the input string is returned unchanged. * The right-to-left case is split out because StringBuilder * doesn't handle right-to-left string building directly very well. */ internal String Replace(Regex regex, String input, int count, int startat) { Match match; if (count < -1) throw new ArgumentOutOfRangeException("count", SR.CountTooSmall); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException("startat", SR.BeginIndexNotNegative); if (count == 0) return input; match = regex.Match(input, startat); if (!match.Success) { return input; } else { StringBuilder sb; if (!regex.RightToLeft) { sb = new StringBuilder(); int prevat = 0; do { if (match.Index != prevat) sb.Append(input, prevat, match.Index - prevat); prevat = match.Index + match.Length; ReplacementImpl(sb, match); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) sb.Append(input, prevat, input.Length - prevat); } else { List<String> al = new List<String>(); int prevat = input.Length; do { if (match.Index + match.Length != prevat) al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; ReplacementImplRTL(al, match); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); sb = new StringBuilder(); if (prevat > 0) sb.Append(input, 0, prevat); for (int i = al.Count - 1; i >= 0; i--) { sb.Append(al[i]); } } return sb.ToString(); } } /* * Replaces all ocurrances of the regex in the string with the * replacement evaluator. * * Note that the special case of no matches is handled on its own: * with no matches, the input string is returned unchanged. * The right-to-left case is split out because StringBuilder * doesn't handle right-to-left string building directly very well. */ internal static String Replace(MatchEvaluator evaluator, Regex regex, String input, int count, int startat) { Match match; if (evaluator == null) throw new ArgumentNullException("evaluator"); if (count < -1) throw new ArgumentOutOfRangeException("count", SR.CountTooSmall); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException("startat", SR.BeginIndexNotNegative); if (count == 0) return input; match = regex.Match(input, startat); if (!match.Success) { return input; } else { StringBuilder sb; if (!regex.RightToLeft) { sb = new StringBuilder(); int prevat = 0; do { if (match.Index != prevat) sb.Append(input, prevat, match.Index - prevat); prevat = match.Index + match.Length; sb.Append(evaluator(match)); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) sb.Append(input, prevat, input.Length - prevat); } else { List<String> al = new List<String>(); int prevat = input.Length; do { if (match.Index + match.Length != prevat) al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; al.Add(evaluator(match)); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); sb = new StringBuilder(); if (prevat > 0) sb.Append(input, 0, prevat); for (int i = al.Count - 1; i >= 0; i--) { sb.Append(al[i]); } } return sb.ToString(); } } /* * Does a split. In the right-to-left case we reorder the * array to be forwards. */ internal static String[] Split(Regex regex, String input, int count, int startat) { Match match; String[] result; if (count < 0) throw new ArgumentOutOfRangeException("count", SR.CountTooSmall); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException("startat", SR.BeginIndexNotNegative); if (count == 1) { result = new String[1]; result[0] = input; return result; } count -= 1; match = regex.Match(input, startat); if (!match.Success) { result = new String[1]; result[0] = input; return result; } else { List<String> al = new List<String>(); if (!regex.RightToLeft) { int prevat = 0; for (; ;) { al.Add(input.Substring(prevat, match.Index - prevat)); prevat = match.Index + match.Length; // add all matched capture groups to the list. for (int i = 1; i < match.Groups.Count; i++) { if (match.IsMatched(i)) al.Add(match.Groups[i].ToString()); } if (--count == 0) break; match = match.NextMatch(); if (!match.Success) break; } al.Add(input.Substring(prevat, input.Length - prevat)); } else { int prevat = input.Length; for (; ;) { al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; // add all matched capture groups to the list. for (int i = 1; i < match.Groups.Count; i++) { if (match.IsMatched(i)) al.Add(match.Groups[i].ToString()); } if (--count == 0) break; match = match.NextMatch(); if (!match.Success) break; } al.Add(input.Substring(0, prevat)); al.Reverse(0, al.Count); } return al.ToArray(); } } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IProductDescriptionOriginalData : ISchemaBaseOriginalData { string Description { get; } string rowguid { get; } } public partial class ProductDescription : OGM<ProductDescription, ProductDescription.ProductDescriptionData, System.String>, ISchemaBase, INeo4jBase, IProductDescriptionOriginalData { #region Initialize static ProductDescription() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, ProductDescription> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.ProductDescriptionAlias, IWhereQuery> query) { q.ProductDescriptionAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.ProductDescription.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"ProductDescription => Description : {this.Description}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new ProductDescriptionData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.Description == null) throw new PersistenceException(string.Format("Cannot save ProductDescription with key '{0}' because the Description cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.rowguid == null) throw new PersistenceException(string.Format("Cannot save ProductDescription with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save ProductDescription with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class ProductDescriptionData : Data<System.String> { public ProductDescriptionData() { } public ProductDescriptionData(ProductDescriptionData data) { Description = data.Description; rowguid = data.rowguid; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "ProductDescription"; } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("Description", Description); dictionary.Add("rowguid", rowguid); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("Description", out value)) Description = (string)value; if (properties.TryGetValue("rowguid", out value)) rowguid = (string)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IProductDescription public string Description { get; set; } public string rowguid { get; set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IProductDescription public string Description { get { LazyGet(); return InnerData.Description; } set { if (LazySet(Members.Description, InnerData.Description, value)) InnerData.Description = value; } } public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static ProductDescriptionMembers members = null; public static ProductDescriptionMembers Members { get { if (members == null) { lock (typeof(ProductDescription)) { if (members == null) members = new ProductDescriptionMembers(); } } return members; } } public class ProductDescriptionMembers { internal ProductDescriptionMembers() { } #region Members for interface IProductDescription public Property Description { get; } = Datastore.AdventureWorks.Model.Entities["ProductDescription"].Properties["Description"]; public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["ProductDescription"].Properties["rowguid"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static ProductDescriptionFullTextMembers fullTextMembers = null; public static ProductDescriptionFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(ProductDescription)) { if (fullTextMembers == null) fullTextMembers = new ProductDescriptionFullTextMembers(); } } return fullTextMembers; } } public class ProductDescriptionFullTextMembers { internal ProductDescriptionFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(ProductDescription)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["ProductDescription"]; } } return entity; } private static ProductDescriptionEvents events = null; public static ProductDescriptionEvents Events { get { if (events == null) { lock (typeof(ProductDescription)) { if (events == null) events = new ProductDescriptionEvents(); } } return events; } } public class ProductDescriptionEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<ProductDescription, EntityEventArgs> onNew; public event EventHandler<ProductDescription, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<ProductDescription, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((ProductDescription)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<ProductDescription, EntityEventArgs> onDelete; public event EventHandler<ProductDescription, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<ProductDescription, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((ProductDescription)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<ProductDescription, EntityEventArgs> onSave; public event EventHandler<ProductDescription, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<ProductDescription, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((ProductDescription)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnDescription private static bool onDescriptionIsRegistered = false; private static EventHandler<ProductDescription, PropertyEventArgs> onDescription; public static event EventHandler<ProductDescription, PropertyEventArgs> OnDescription { add { lock (typeof(OnPropertyChange)) { if (!onDescriptionIsRegistered) { Members.Description.Events.OnChange -= onDescriptionProxy; Members.Description.Events.OnChange += onDescriptionProxy; onDescriptionIsRegistered = true; } onDescription += value; } } remove { lock (typeof(OnPropertyChange)) { onDescription -= value; if (onDescription == null && onDescriptionIsRegistered) { Members.Description.Events.OnChange -= onDescriptionProxy; onDescriptionIsRegistered = false; } } } } private static void onDescriptionProxy(object sender, PropertyEventArgs args) { EventHandler<ProductDescription, PropertyEventArgs> handler = onDescription; if ((object)handler != null) handler.Invoke((ProductDescription)sender, args); } #endregion #region Onrowguid private static bool onrowguidIsRegistered = false; private static EventHandler<ProductDescription, PropertyEventArgs> onrowguid; public static event EventHandler<ProductDescription, PropertyEventArgs> Onrowguid { add { lock (typeof(OnPropertyChange)) { if (!onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; Members.rowguid.Events.OnChange += onrowguidProxy; onrowguidIsRegistered = true; } onrowguid += value; } } remove { lock (typeof(OnPropertyChange)) { onrowguid -= value; if (onrowguid == null && onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; onrowguidIsRegistered = false; } } } } private static void onrowguidProxy(object sender, PropertyEventArgs args) { EventHandler<ProductDescription, PropertyEventArgs> handler = onrowguid; if ((object)handler != null) handler.Invoke((ProductDescription)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<ProductDescription, PropertyEventArgs> onModifiedDate; public static event EventHandler<ProductDescription, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<ProductDescription, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((ProductDescription)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<ProductDescription, PropertyEventArgs> onUid; public static event EventHandler<ProductDescription, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<ProductDescription, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((ProductDescription)sender, args); } #endregion } #endregion } #endregion #region IProductDescriptionOriginalData public IProductDescriptionOriginalData OriginalVersion { get { return this; } } #region Members for interface IProductDescription string IProductDescriptionOriginalData.Description { get { return OriginalData.Description; } } string IProductDescriptionOriginalData.rowguid { get { return OriginalData.rowguid; } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
using System; using Eto.Drawing; using Eto.Forms; #if XAMMAC2 using AppKit; using Foundation; using CoreGraphics; using ObjCRuntime; using CoreAnimation; using CoreImage; #else using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.CoreGraphics; using MonoMac.ObjCRuntime; using MonoMac.CoreAnimation; using MonoMac.CoreImage; #if Mac64 using CGSize = MonoMac.Foundation.NSSize; using CGRect = MonoMac.Foundation.NSRect; using CGPoint = MonoMac.Foundation.NSPoint; using nfloat = System.Double; using nint = System.Int64; using nuint = System.UInt64; #else using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using nfloat = System.Single; using nint = System.Int32; using nuint = System.UInt32; #endif #endif namespace Eto.Mac.Forms.Controls { /// <summary> /// Button handler. /// </summary> /// <copyright>(c) 2012-2013 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class ButtonHandler : MacButton<NSButton, Button, Button.ICallback>, Button.IHandler { Image image; ButtonImagePosition imagePosition; static readonly Size originalSize; public static int MinimumWidth = 80; public class EtoButtonCell : NSButtonCell { public Color? Color { get; set; } public override void DrawBezelWithFrame(CGRect frame, NSView controlView) { if (Color != null) { MacEventView.Colourize(controlView, Color.Value, delegate { base.DrawBezelWithFrame(frame, controlView); }); } else base.DrawBezelWithFrame(frame, controlView); } } class EtoButton : NSButton, IMacControl { bool setBezel = true; public WeakReference WeakHandler { get; set; } public ButtonHandler Handler { get { return (ButtonHandler)WeakHandler.Target; } set { WeakHandler = new WeakReference(value); } } public override void SizeToFit() { setBezel = false; base.SizeToFit(); if (Handler.AutoSize) { var size = Frame.Size; size.Width = (nfloat)Math.Max(size.Width, MinimumWidth); SetFrameSize(size); } setBezel = true; } public override void SetFrameSize(CGSize newSize) { base.SetFrameSize(newSize); if (setBezel) Handler.SetBezel(); } } static ButtonHandler() { // store the normal size for a rounded button, so we can determine what style to give it based on actual size var b = new NSButton { BezelStyle = NSBezelStyle.Rounded }; b.SizeToFit(); originalSize = b.Frame.Size.ToEtoSize(); } public ButtonHandler() { Control = new EtoButton { Handler = this, Cell = new EtoButtonCell (), Title = string.Empty, BezelStyle = NSBezelStyle.Rounded, ImagePosition = NSCellImagePosition.ImageLeft }; Control.SetButtonType(NSButtonType.MomentaryPushIn); Control.Activated += HandleActivated; } public override void OnLoadComplete(EventArgs e) { base.OnLoadComplete(e); SetBezel(); } static void HandleActivated(object sender, EventArgs e) { var handler = GetHandler(sender) as ButtonHandler; if (handler != null) { handler.Callback.OnClick(handler.Widget, EventArgs.Empty); } } public override void AttachEvent(string id) { switch (id) { default: base.AttachEvent(id); break; } } public override Color BackgroundColor { get { var cell = (EtoButtonCell)Control.Cell; return cell.Color ?? Colors.Transparent; } set { var cell = (EtoButtonCell)Control.Cell; cell.Color = value.A > 0 ? (Color?)value : null; Control.SetNeedsDisplay(); } } public Image Image { get { return image; } set { var oldSize = GetPreferredSize(Size.MaxValue); image = value; Control.Image = image.ToNS(); SetBezel(); LayoutIfNeeded(oldSize); } } public override Size Size { get { return base.Size; } set { base.Size = value; SetBezel(); } } /// <summary> /// Gets the bezel style of the button based on its size and image position /// </summary> NSBezelStyle GetBezelStyle() { var size = Control.Frame.Size.ToEtoSize(); if (size.Width == 0 || size.Height == 0) return Control.BezelStyle; if (size.Height < 22 || size.Width < 22) return NSBezelStyle.SmallSquare; if (size.Height > originalSize.Height) return NSBezelStyle.RegularSquare; if (Image == null) return NSBezelStyle.Rounded; if (image.Size.Height > 18) return NSBezelStyle.RegularSquare; switch (Control.ImagePosition) { case NSCellImagePosition.ImageAbove: case NSCellImagePosition.ImageBelow: if (!string.IsNullOrEmpty(Text)) return NSBezelStyle.RegularSquare; break; } return NSBezelStyle.Rounded; } void SetBezel() { Control.BezelStyle = GetBezelStyle(); } public override string Text { get { return base.Text; } set { base.Text = value; SetImagePosition(); } } void SetImagePosition() { var position = imagePosition.ToNS(); if ((position == NSCellImagePosition.ImageAbove || position == NSCellImagePosition.ImageBelow) && string.IsNullOrEmpty(Text)) position = NSCellImagePosition.ImageOnly; Control.ImagePosition = position; SetBezel(); } public ButtonImagePosition ImagePosition { get { return imagePosition; } set { if (imagePosition != value) { var oldSize = GetPreferredSize(Size.MaxValue); imagePosition = value; SetImagePosition(); LayoutIfNeeded(oldSize); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Vec2 { [TestFixture] public class LongVec2Test { [Test] public void Constructors() { { var v = new lvec2(2L); Assert.AreEqual(2L, v.x); Assert.AreEqual(2L, v.y); } { var v = new lvec2(1, 9L); Assert.AreEqual(1, v.x); Assert.AreEqual(9L, v.y); } { var v = new lvec2(new lvec2(3L, -2L)); Assert.AreEqual(3L, v.x); Assert.AreEqual(-2L, v.y); } { var v = new lvec2(new lvec3(-8L, 1, -9L)); Assert.AreEqual(-8L, v.x); Assert.AreEqual(1, v.y); } { var v = new lvec2(new lvec4(6L, 6L, -9L, -4L)); Assert.AreEqual(6L, v.x); Assert.AreEqual(6L, v.y); } } [Test] public void Indexer() { var v = new lvec2(2L, -2L); Assert.AreEqual(2L, v[0]); Assert.AreEqual(-2L, v[1]); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-2147483648]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[-2147483648] = 0; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-1]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[-1] = 0; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[2]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[2] = 0; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[2147483647]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[2147483647] = 0; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[5]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[5] = 0; } ); v[1] = 0; Assert.AreEqual(0, v[1]); v[0] = 1; Assert.AreEqual(1, v[0]); v[0] = 2L; Assert.AreEqual(2L, v[0]); v[0] = 3L; Assert.AreEqual(3L, v[0]); v[1] = 4L; Assert.AreEqual(4L, v[1]); v[0] = 5L; Assert.AreEqual(5L, v[0]); v[1] = 6L; Assert.AreEqual(6L, v[1]); v[0] = 7L; Assert.AreEqual(7L, v[0]); v[1] = 8L; Assert.AreEqual(8L, v[1]); v[0] = 9L; Assert.AreEqual(9L, v[0]); v[0] = -1L; Assert.AreEqual(-1L, v[0]); v[0] = -2L; Assert.AreEqual(-2L, v[0]); v[1] = -3L; Assert.AreEqual(-3L, v[1]); v[1] = -4L; Assert.AreEqual(-4L, v[1]); v[1] = -5L; Assert.AreEqual(-5L, v[1]); v[0] = -6L; Assert.AreEqual(-6L, v[0]); v[0] = -7L; Assert.AreEqual(-7L, v[0]); v[1] = -8L; Assert.AreEqual(-8L, v[1]); v[1] = -9L; Assert.AreEqual(-9L, v[1]); } [Test] public void PropertyValues() { var v = new lvec2(9L, 9L); var vals = v.Values; Assert.AreEqual(9L, vals[0]); Assert.AreEqual(9L, vals[1]); Assert.That(vals.SequenceEqual(v.ToArray())); } [Test] public void StaticProperties() { Assert.AreEqual(0, lvec2.Zero.x); Assert.AreEqual(0, lvec2.Zero.y); Assert.AreEqual(1, lvec2.Ones.x); Assert.AreEqual(1, lvec2.Ones.y); Assert.AreEqual(1, lvec2.UnitX.x); Assert.AreEqual(0, lvec2.UnitX.y); Assert.AreEqual(0, lvec2.UnitY.x); Assert.AreEqual(1, lvec2.UnitY.y); Assert.AreEqual(long.MaxValue, lvec2.MaxValue.x); Assert.AreEqual(long.MaxValue, lvec2.MaxValue.y); Assert.AreEqual(long.MinValue, lvec2.MinValue.x); Assert.AreEqual(long.MinValue, lvec2.MinValue.y); } [Test] public void Operators() { var v1 = new lvec2(9L, -1L); var v2 = new lvec2(9L, -1L); var v3 = new lvec2(-1L, 9L); Assert.That(v1 == new lvec2(v1)); Assert.That(v2 == new lvec2(v2)); Assert.That(v3 == new lvec2(v3)); Assert.That(v1 == v2); Assert.That(v1 != v3); Assert.That(v2 != v3); } [Test] public void StringInterop() { var v = new lvec2(-2L, 6L); var s0 = v.ToString(); var s1 = v.ToString("#"); var v0 = lvec2.Parse(s0); var v1 = lvec2.Parse(s1, "#"); Assert.AreEqual(v, v0); Assert.AreEqual(v, v1); var b0 = lvec2.TryParse(s0, out v0); var b1 = lvec2.TryParse(s1, "#", out v1); Assert.That(b0); Assert.That(b1); Assert.AreEqual(v, v0); Assert.AreEqual(v, v1); b0 = lvec2.TryParse(null, out v0); Assert.False(b0); b0 = lvec2.TryParse("", out v0); Assert.False(b0); b0 = lvec2.TryParse(s0 + ", 0", out v0); Assert.False(b0); Assert.Throws<NullReferenceException>(() => { lvec2.Parse(null); }); Assert.Throws<FormatException>(() => { lvec2.Parse(""); }); Assert.Throws<FormatException>(() => { lvec2.Parse(s0 + ", 0"); }); var s2 = v.ToString(";", CultureInfo.InvariantCulture); Assert.That(s2.Length > 0); var s3 = v.ToString("; ", "G"); var s4 = v.ToString("; ", "G", CultureInfo.InvariantCulture); var v3 = lvec2.Parse(s3, "; ", NumberStyles.Number); var v4 = lvec2.Parse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture); Assert.AreEqual(v, v3); Assert.AreEqual(v, v4); var b4 = lvec2.TryParse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture, out v4); Assert.That(b4); Assert.AreEqual(v, v4); } [Test] public void SerializationJson() { var v0 = new lvec2(9L, 6L); var s0 = JsonConvert.SerializeObject(v0); var v1 = JsonConvert.DeserializeObject<lvec2>(s0); var s1 = JsonConvert.SerializeObject(v1); Assert.AreEqual(v0, v1); Assert.AreEqual(s0, s1); } [Test] public void InvariantId() { { var v0 = new lvec2(-8L, -9L); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(-4L, -1L); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(6L, -9L); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(-2L, 0); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(-9L, -2L); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(5L, -7L); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(8L, 7L); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(-3L, 0); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(-5L, 2L); Assert.AreEqual(v0, +v0); } { var v0 = new lvec2(-7L, 2L); Assert.AreEqual(v0, +v0); } } [Test] public void InvariantDouble() { { var v0 = new lvec2(3L, 3L); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(-5L, -1L); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(-7L, 0); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(-4L, -4L); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(-7L, 4L); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(9L, -3L); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(-5L, 4L); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(1, -1L); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(-6L, -2L); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new lvec2(9L, -7L); Assert.AreEqual(v0 + v0, 2 * v0); } } [Test] public void InvariantTriple() { { var v0 = new lvec2(-6L, 2L); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(4L, 1); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(4L, 1); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(8L, 4L); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(-1L, -5L); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(-1L, -6L); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(9L, -7L); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(3L, 8L); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(-5L, -4L); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new lvec2(8L, 5L); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } } [Test] public void InvariantCommutative() { { var v0 = new lvec2(-2L, 6L); var v1 = new lvec2(-6L, 8L); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(-4L, -9L); var v1 = new lvec2(9L, 0); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(6L, 6L); var v1 = new lvec2(-3L, -2L); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(4L, -6L); var v1 = new lvec2(1, -9L); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(-2L, 3L); var v1 = new lvec2(1, -7L); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(-9L, 0); var v1 = new lvec2(6L, -4L); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(0, -5L); var v1 = new lvec2(-8L, 2L); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(0, 6L); var v1 = new lvec2(7L, -2L); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(5L, -5L); var v1 = new lvec2(4L, 9L); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new lvec2(-2L, -1L); var v1 = new lvec2(-3L, 5L); Assert.AreEqual(v0 * v1, v1 * v0); } } [Test] public void InvariantAssociative() { { var v0 = new lvec2(-9L, -7L); var v1 = new lvec2(-7L, 6L); var v2 = new lvec2(-1L, -3L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(4L, 8L); var v1 = new lvec2(9L, -3L); var v2 = new lvec2(1, -8L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(-4L, 4L); var v1 = new lvec2(-8L, 2L); var v2 = new lvec2(-2L, -3L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(-1L, 6L); var v1 = new lvec2(-3L, -2L); var v2 = new lvec2(-8L, -5L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(2L, -3L); var v1 = new lvec2(-3L, -7L); var v2 = new lvec2(-4L, -9L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(-6L, 0); var v1 = new lvec2(4L, -8L); var v2 = new lvec2(-9L, -4L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(-4L, 4L); var v1 = new lvec2(8L, -5L); var v2 = new lvec2(8L, -1L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(8L, -7L); var v1 = new lvec2(-7L, -6L); var v2 = new lvec2(2L, 9L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(-9L, -1L); var v1 = new lvec2(-2L, 3L); var v2 = new lvec2(-2L, 3L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new lvec2(-3L, 7L); var v1 = new lvec2(-8L, 1); var v2 = new lvec2(4L, -8L); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } } [Test] public void InvariantIdNeg() { { var v0 = new lvec2(-9L, 3L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(-9L, 7L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(4L, -8L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(-6L, -4L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(5L, -8L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(4L, 8L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(-9L, -1L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(-1L, 6L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(-5L, -4L); Assert.AreEqual(v0, -(-v0)); } { var v0 = new lvec2(-8L, -6L); Assert.AreEqual(v0, -(-v0)); } } [Test] public void InvariantCommutativeNeg() { { var v0 = new lvec2(-6L, -2L); var v1 = new lvec2(-2L, 5L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(-6L, -7L); var v1 = new lvec2(-9L, 8L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(-2L, 6L); var v1 = new lvec2(-1L, 9L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(-1L, 7L); var v1 = new lvec2(1, -8L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(9L, 6L); var v1 = new lvec2(9L, -2L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(7L, -6L); var v1 = new lvec2(-7L, 2L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(-9L, 9L); var v1 = new lvec2(7L, -1L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(-5L, 5L); var v1 = new lvec2(0, 9L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(2L, -9L); var v1 = new lvec2(1, 1); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new lvec2(-6L, -6L); var v1 = new lvec2(6L, -9L); Assert.AreEqual(v0 - v1, -(v1 - v0)); } } [Test] public void InvariantAssociativeNeg() { { var v0 = new lvec2(9L, -7L); var v1 = new lvec2(0, -5L); var v2 = new lvec2(-4L, -7L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(8L, 4L); var v1 = new lvec2(-4L, -9L); var v2 = new lvec2(-8L, -7L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(-9L, 0); var v1 = new lvec2(-3L, -8L); var v2 = new lvec2(-9L, 1); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(1, 5L); var v1 = new lvec2(3L, 7L); var v2 = new lvec2(-1L, -4L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(-9L, -7L); var v1 = new lvec2(8L, 0); var v2 = new lvec2(1, 5L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(-4L, -3L); var v1 = new lvec2(8L, -3L); var v2 = new lvec2(0, 3L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(-2L, 7L); var v1 = new lvec2(7L, -6L); var v2 = new lvec2(7L, -8L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(-5L, -5L); var v1 = new lvec2(-2L, -4L); var v2 = new lvec2(2L, -3L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(-5L, 3L); var v1 = new lvec2(-1L, -7L); var v2 = new lvec2(6L, -3L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new lvec2(-8L, 1); var v1 = new lvec2(5L, 5L); var v2 = new lvec2(-6L, -7L); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } } [Test] public void TriangleInequality() { { var v0 = new lvec2(8L, -4L); var v1 = new lvec2(-2L, -6L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(-6L, -6L); var v1 = new lvec2(7L, -4L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(7L, -3L); var v1 = new lvec2(-7L, 2L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(-1L, -7L); var v1 = new lvec2(6L, -9L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(-3L, 1); var v1 = new lvec2(-8L, 8L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(0, -3L); var v1 = new lvec2(-7L, -8L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(0, 5L); var v1 = new lvec2(-5L, 2L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(-8L, -8L); var v1 = new lvec2(-7L, -5L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(7L, -5L); var v1 = new lvec2(-5L, -7L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new lvec2(5L, 6L); var v1 = new lvec2(-4L, 6L); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } } [Test] public void InvariantNorm() { { var v0 = new lvec2(-2L, -5L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(6L, 9L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(-1L, 4L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(-3L, -5L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(-7L, 8L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(2L, -9L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(-7L, 9L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(0, 3L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(-4L, 4L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new lvec2(-1L, -4L); Assert.LessOrEqual(v0.NormMax, v0.Norm); } } [Test] public void RandomUniform0() { var random = new Random(95269133); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.Random(random, -1, 1); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, -0.5, 1.0); Assert.AreEqual(avg.y, -0.5, 1.0); Assert.AreEqual(variance.x, 0.25, 3.0); Assert.AreEqual(variance.y, 0.25, 3.0); } [Test] public void RandomUniform1() { var random = new Random(813837135); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.RandomUniform(random, -4, 1); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, -2, 1.0); Assert.AreEqual(avg.y, -2, 1.0); Assert.AreEqual(variance.x, 2, 3.0); Assert.AreEqual(variance.y, 2, 3.0); } [Test] public void RandomUniform2() { var random = new Random(1532405137); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.Random(random, 1, 6); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 3, 1.0); Assert.AreEqual(avg.y, 3, 1.0); Assert.AreEqual(variance.x, 2, 3.0); Assert.AreEqual(variance.y, 2, 3.0); } [Test] public void RandomUniform3() { var random = new Random(103489492); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.RandomUniform(random, -4, -2); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, -3.5, 1.0); Assert.AreEqual(avg.y, -3.5, 1.0); Assert.AreEqual(variance.x, 0.25, 3.0); Assert.AreEqual(variance.y, 0.25, 3.0); } [Test] public void RandomUniform4() { var random = new Random(1515964419); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.Random(random, 1, 3); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 1.5, 1.0); Assert.AreEqual(avg.y, 1.5, 1.0); Assert.AreEqual(variance.x, 0.25, 3.0); Assert.AreEqual(variance.y, 0.25, 3.0); } [Test] public void RandomPoisson0() { var random = new Random(278502557); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.RandomPoisson(random, 0.615427033563809); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 0.615427033563809, 1.0); Assert.AreEqual(avg.y, 0.615427033563809, 1.0); Assert.AreEqual(variance.x, 0.615427033563809, 3.0); Assert.AreEqual(variance.y, 0.615427033563809, 3.0); } [Test] public void RandomPoisson1() { var random = new Random(997070559); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.RandomPoisson(random, 1.14525588399044); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 1.14525588399044, 1.0); Assert.AreEqual(avg.y, 1.14525588399044, 1.0); Assert.AreEqual(variance.x, 1.14525588399044, 3.0); Assert.AreEqual(variance.y, 1.14525588399044, 3.0); } [Test] public void RandomPoisson2() { var random = new Random(988850200); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.RandomPoisson(random, 2.69768873751056); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 2.69768873751056, 1.0); Assert.AreEqual(avg.y, 2.69768873751056, 1.0); Assert.AreEqual(variance.x, 2.69768873751056, 3.0); Assert.AreEqual(variance.y, 2.69768873751056, 3.0); } [Test] public void RandomPoisson3() { var random = new Random(1707418202); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.RandomPoisson(random, 1.0403901769502); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 1.0403901769502, 1.0); Assert.AreEqual(avg.y, 1.0403901769502, 1.0); Assert.AreEqual(variance.x, 1.0403901769502, 3.0); Assert.AreEqual(variance.y, 1.0403901769502, 3.0); } [Test] public void RandomPoisson4() { var random = new Random(1699197843); var sum = new dvec2(0.0); var sumSqr = new dvec2(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = lvec2.RandomPoisson(random, 2.59282303047032); sum += (dvec2)v; sumSqr += glm.Pow2((dvec2)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 2.59282303047032, 1.0); Assert.AreEqual(avg.y, 2.59282303047032, 1.0); Assert.AreEqual(variance.x, 2.59282303047032, 3.0); Assert.AreEqual(variance.y, 2.59282303047032, 3.0); } } }
using System; using System.Diagnostics; using System.Collections; using HtmlHelp.ChmDecoding; namespace HtmlHelp { /// <summary> /// Enumeration for specifying the index type /// </summary> public enum IndexType { /// <summary> /// Keyword links should be used /// </summary> KeywordLinks = 0, /// <summary> /// Associative links should be used /// </summary> AssiciativeLinks = 1 } /// <summary> /// The class <c>Index</c> holds the (keyword links) KLinks and (associative links) ALinks of the htmlhelp /// system. It implements methods for easy index-based searching. /// </summary> public class Index { private ArrayList _kLinks = new ArrayList(); private ArrayList _aLinks = new ArrayList(); /// <summary> /// Standard constructor /// </summary> public Index() { } /// <summary> /// Constructor of the class /// </summary> /// <param name="kLinks">arraylist with keyword links</param> /// <param name="aLinks">arraylist with associative links</param> public Index(ArrayList kLinks, ArrayList aLinks) { _kLinks= kLinks; _aLinks = aLinks; } /// <summary> /// Clears the current toc /// </summary> public void Clear() { if(_aLinks != null) _aLinks.Clear(); if(_kLinks != null) _kLinks.Clear(); } /// <summary> /// Gets the number of index items for a specific type /// </summary> /// <param name="typeOfIndex">type of index</param> /// <returns>Returns the number of index items for a specific type</returns> public int Count(IndexType typeOfIndex) { ArrayList _index = null; switch( typeOfIndex ) { case IndexType.AssiciativeLinks: _index = _aLinks; break; case IndexType.KeywordLinks: _index = _kLinks; break; } if(_index != null) return _index.Count; return 0; } /// <summary> /// Gets the internal index list of keyword links /// </summary> public ArrayList KLinks { get { if(_kLinks==null) _kLinks = new ArrayList(); return _kLinks; } } /// <summary> /// Gets the internal index list of associative links /// </summary> public ArrayList ALinks { get { if(_aLinks==null) _aLinks = new ArrayList(); return _aLinks; } } /// <summary> /// Merges the the index list <c>arrIndex</c> into the current one /// </summary> /// <param name="arrIndex">indexlist which should be merged with the current one</param> /// <param name="typeOfIndex">type of index to merge</param> public void MergeIndex( ArrayList arrIndex, IndexType typeOfIndex ) { ArrayList _index = null; switch(typeOfIndex) { case IndexType.AssiciativeLinks: _index = _aLinks;break; case IndexType.KeywordLinks: _index = _kLinks;break; } Debug.WriteLine("Index.MergeIndex() "); Debug.Indent(); DateTime dtStartM = DateTime.Now; foreach(IndexItem curItem in arrIndex) { //IndexItem searchItem = ContainsIndex(_index, curItem.KeyWordPath); int insertIndex=0; IndexItem searchItem = BinSearch(0, _index.Count-1, _index, curItem.KeyWordPath, false, false, ref insertIndex); if(searchItem != null) { // extend the keywords topics foreach(IndexTopic curEntry in curItem.Topics) { searchItem.Topics.Add( curEntry ); } } else { // add the item to the global collection //_index.Add( curItem ); if(insertIndex > _index.Count) _index.Add(curItem); else _index.Insert(insertIndex, curItem); } } DateTime dtEndM = DateTime.Now; TimeSpan elapsedM = dtEndM-dtStartM; Debug.WriteLine("--- Merge completed in " + elapsedM.ToString()); Debug.Unindent(); } /// <summary> /// Searches an index entry using recursive binary search algo (divide and conquer). /// </summary> /// <param name="nStart">start index for searching</param> /// <param name="nEnd">end index for searching</param> /// <param name="arrIndex">arraylist containing sorted IndexItem entries</param> /// <param name="keywordPath">keyword path to search</param> /// <param name="searchKeyword">true if the keywordPath will only contain the keyword not the complete path</param> /// <param name="caseInsensitive">True if case should be ignored</param> /// <param name="insertIndex">out reference. will receive the index where the item with the /// keywordPath should be inserted if not found (receives -1 if the item was found)</param> /// <returns>Returns an IndexItem instance if found, otherwise null /// (use insertIndex for inserting the new item in a sorted order)</returns> private IndexItem BinSearch(int nStart, int nEnd, ArrayList arrIndex, string keywordPath, bool searchKeyword, bool caseInsensitive, ref int insertIndex) { if( arrIndex.Count <= 0 ) { insertIndex=0; return null; } if(caseInsensitive) keywordPath = keywordPath.ToLower(); if( (nEnd - nStart) > 1) { int nCheck = nStart + (nEnd-nStart)/2; IndexItem iC = arrIndex[nCheck] as IndexItem; string sCompare = iC.KeyWordPath; if(searchKeyword) sCompare = iC.KeyWord; if(caseInsensitive) sCompare = sCompare.ToLower(); if( sCompare == keywordPath ) { insertIndex=-1; return iC; } if( keywordPath.CompareTo(sCompare) < 0 ) { return BinSearch(nStart, nCheck-1, arrIndex, keywordPath, searchKeyword, caseInsensitive, ref insertIndex); } if( keywordPath.CompareTo(sCompare) > 0 ) { return BinSearch(nCheck+1, nEnd, arrIndex, keywordPath, searchKeyword, caseInsensitive, ref insertIndex); } } else if(nEnd-nStart == 1) { IndexItem i1 = arrIndex[nStart] as IndexItem; IndexItem i2 = arrIndex[nEnd] as IndexItem; string sCompare1 = i1.KeyWordPath; if(searchKeyword) sCompare1 = i1.KeyWord; if(caseInsensitive) sCompare1 = sCompare1.ToLower(); string sCompare2 = i2.KeyWordPath; if(searchKeyword) sCompare2 = i2.KeyWord; if(caseInsensitive) sCompare2 = sCompare2.ToLower(); if( sCompare1 == keywordPath) { insertIndex = -1; return i1; } if( sCompare2 == keywordPath) { insertIndex = -1; return i2; } if( sCompare1.CompareTo(keywordPath) > 0) { insertIndex = nStart; return null; } else if( sCompare2.CompareTo(keywordPath) > 0) { insertIndex = nEnd; return null; } else { insertIndex = nEnd+1; } } IndexItem itm = arrIndex[nEnd] as IndexItem; string sCompareI = itm.KeyWordPath; if(searchKeyword) sCompareI = itm.KeyWord; if(caseInsensitive) sCompareI = sCompareI.ToLower(); if( sCompareI.CompareTo(keywordPath) > 0) { insertIndex = nStart; return null; } else if( sCompareI.CompareTo(keywordPath) < 0) { insertIndex = nEnd+1; return null; } else { insertIndex = -1; return arrIndex[nEnd] as IndexItem; } } /// <summary> /// Checks if a keyword exists in a index collection /// </summary> /// <param name="arrIndex">index to search (arraylist of IndexItems)</param> /// <param name="keywordPath">keywordpath to search</param> /// <returns>Returns the found IndexItem, otherwise null</returns> private IndexItem ContainsIndex(ArrayList arrIndex, string keywordPath) { foreach(IndexItem curItem in arrIndex) { if(curItem.KeyWordPath == keywordPath) return curItem; } return null; } /// <summary> /// Searches the alinks- or klinks-index for a specific keyword/associative /// </summary> /// <param name="search">keyword/associative to search</param> /// <param name="typeOfIndex">type of index to search</param> /// <returns>Returns an ArrayList which contains IndexTopic items or null if nothing was found</returns> public IndexItem SearchIndex(string search, IndexType typeOfIndex) { ArrayList _index = null; switch( typeOfIndex ) { case IndexType.AssiciativeLinks: _index = _aLinks;break; case IndexType.KeywordLinks: _index = _kLinks;break; } int insertIdx=0; IndexItem foundItem = BinSearch(0, _index.Count, _index, search, true, true, ref insertIdx); return foundItem; } } }
using SimpleJSON; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; /* Created by Yumashish Subba * I cannot be bothered to make a license, please just drop my name in there somewhere * so that the next unfortunate soul who has to read through our (or my, if you're that good) god awful code can know exactly * who messed up their day. * * IT WAS ME. */ namespace YumaWebLib.Json { public class JsonObject : SilenceableLoggingObject { JsonObject() { Log ("You can disable log messages by setting the bool value BE_QUIET to true"); } public class DemoJsonObject { [YWLKey()] public int id; [YWLKey()] public string name; [YWLKey("ListAddr")] public List<string> list; [YWLKey("InnerObject")] public InnerObject obj; public class InnerObject { [YWLKey()] public int id; [YWLKey()] public List<WeHaveToGoDeeper> chinkystare; public class WeHaveToGoDeeper { [YWLKey()] public double french_horn; } } } public class ListDemoJsonObject { [YWLKey("id")] public int _id; [YWLKey()] public int uid; [YWLKey("public")] public int isPublic; [YWLKey()] public string name; [YWLKey()] public string creation_date; [YWLKey()] public string start_code; [YWLKey()] public string run_code; [YWLKey()] public string data; } public static string DemoJsonObjectJSON() { return "{\"id\":\"1\", \"name\":\"object name\", \"ListAddr\":[\"1\", \"2\", \"3\"], \"InnerObject\":{\"id\":\"42\", \"chinkystare\":[{\"french_horn\":\"234.34534\"}, {\"french\":\"44.454\"}]}}"; } public static string DemoListJsonObjectJSON() { return "[{\"id\":\"4\",\"uid\":\"1\",\"public\":\"1\",\"name\":\"Starfighter\",\"data\":\"\",\"creation_date\":\"2015-10-21 06:40:54\",\"start_code\":null,\"run_code\":null},{\"id\":\"5\",\"uid\":\"1\",\"public\":\"0\",\"name\":\"Warfighter\",\"data\":\"\",\"creation_date\":\"2015-10-21 06:40:54\",\"start_code\":null,\"run_code\":null}]"; } public static JsonObject JsonObjectFactoryFactoryBuilderFactory() { //harhar return new JsonObject(); } //jsonify methods public string ToJSON(Object o) { return ObjectToJSON(o); } string FieldToJSON(FieldInfo field, object classObject) { string fieldName = field.Name; bool isKey = false; Attribute[] attrs = Attribute.GetCustomAttributes (field); foreach (Attribute attr in attrs) { if(attr is YWLKey) { isKey = true; YWLKey key = (YWLKey) attr; if(key.name.Length > 0) { fieldName = key.name; break; } } } Log ("-------------- Parsing field " + fieldName + " (" + field.FieldType + ") ---------------------"); if (!isKey) { Log ("Field is not a Key!"); Log ("-------------- Parsing field " + fieldName + " ---------------------"); return ""; } return ItemToJSON (field.GetValue (classObject), field.FieldType); //return null; } string ItemToJSON(object item, Type itemType) { Log ("--Extracting item value for type (" + itemType + ")--"); //Type itemType = itemObject.GetType (); if (itemType.IsPrimitive || itemType.Equals (typeof(string))) { return "\"" + item + "\""; } else if (itemType.IsArray) { throw new Exception ("This library does not handle basic arrays, please use a List instead."); } else if(itemType.IsGenericType) { Log ("Item is a generic type"); if(itemType.GetGenericTypeDefinition() == typeof(List<>)) { //Type listType = itemType.GetGenericArguments()[0]; return ListToJSON((IList) item); } } else { Log ("Item is an object type"); //nested jsonobject object object nestedObject = Activator.CreateInstance(itemType); return ObjectToJSON(item); } throw new Exception ("Field " + itemType + " cannot be handled by this library, you'll have to implement this yourself"); } string ObjectToJSON(object item) { string final = "{"; int cut = 0; foreach (FieldInfo field in item.GetType().GetFields()) { final += "\"" + field.Name + "\" : " + FieldToJSON(field, item) + ", "; cut = 2; } final = final.Substring (0, final.Length - cut); return final + "}"; } public string ListToJSON(IList list) { string final = "["; Type listType = list.GetType().GetGenericArguments()[0]; int cut = 0; foreach (object item in list) { final += ItemToJSON (item, listType) + ", "; cut = 2; } final = final.Substring (0, final.Length - cut); return final + "]"; } //-----------Parsing methods----------- public T Parse<T>(string json, T classObject) { JSONNode root = JSON.Parse (json); //if array string firstChar = json.Substring(0, 1); if (firstChar == "{") { return (T)ExtractObject (root, classObject); } else if (firstChar == "[") { if (classObject.GetType ().IsGenericType && classObject.GetType ().GetGenericTypeDefinition () == typeof(List<>)) return (T)ExtractList (root, (IList) classObject); else throw new Exception ("The json object is an array, you must pass a List<> object"); } else { return (T)ExtractItem (root, typeof(T)); } } void ExtractField(JSONNode node, FieldInfo field, ref object classObject) { string fieldName = field.Name; bool isKey = false; Attribute[] attrs = Attribute.GetCustomAttributes (field); foreach (Attribute attr in attrs) { if(attr is YWLKey) { isKey = true; YWLKey key = (YWLKey) attr; if(key.name.Length > 0) { fieldName = key.name; break; } } } Log ("-------------- Parsing field " + fieldName + " (" + field.FieldType + ") ---------------------"); if (!isKey) { Log ("Field is not a Key!"); Log ("-------------- Parsing field " + fieldName + " ---------------------"); return; } Log ("Raw value for field name: " + node [fieldName]); object fieldObject; if (node[fieldName] != null) { fieldObject = ExtractItem (node [fieldName], field.FieldType); Log ("Field resolved value: " + fieldObject); } else { if(field.FieldType.Equals(typeof(string))) { string fo = ""; fieldObject = fo; } else { try{ fieldObject = Activator.CreateInstance (field.FieldType); } catch (MissingMethodException mme) { fieldObject = null; } } Log ("No json value for this key + " + fieldName + " +, using default value"); } field.SetValue(classObject, Convert.ChangeType(fieldObject, field.FieldType)); Log ("-------------- Parsing field " + fieldName + " ---------------------"); } object ExtractItem(JSONNode node, Type itemType) { Log ("--Extracting item value for type (" + itemType + ")--"); //Type itemType = itemObject.GetType (); if (itemType.IsPrimitive) { Log ("Item is a primitive type, typecode " + Type.GetTypeCode(itemType)); if (IsNumericTypeNullable (itemType)) { Log ("Item is numeric"); Double d; if (Double.TryParse (node.Value, out d)) { return Convert.ChangeType (d, itemType); } else { throw new Exception ("The provided JSON Node does not contain a readable numeric field" + ". [Be advised that because of my laziness, all numeric fields are initially casted into" + "a double then into other data types. If the numeric value in your json is say, a BigInt or " + "BigRational you will need to implement this yourself.] [Actual Value: " + node.Value + "]"); } } else if (itemType.Equals (typeof(bool))) { Log ("Item is boolean"); return node.AsBool; } else { Log ("Item is unknown primitive"); } } else if (itemType.IsArray) { throw new Exception ("This library does not handle basic arrays, please use a List instead."); } else if (itemType.Equals (typeof(string))) { Log ("Item is a string type"); return node.Value; } else if(itemType.IsGenericType) { Log ("Item is a generic type"); if(itemType.GetGenericTypeDefinition() == typeof(List<>)) { //Type listType = itemType.GetGenericArguments()[0]; return ExtractList(node, (IList) Activator.CreateInstance(itemType)); } } else { Log ("Item is an object type"); //nested jsonobject object object nestedObject = Activator.CreateInstance(itemType); return ExtractObject(node, nestedObject); } throw new Exception ("Field " + itemType + " cannot be handled by this library, you'll have to implement this yourself"); //return null; } object ExtractObject(JSONNode node, object classObject) { Log ("========== Parsing object " + classObject.GetType ().Name + " ====================="); Log ("Fields found (" + classObject.GetType().GetFields().Length + ")"); foreach(FieldInfo field in classObject.GetType().GetFields()) { Log (field.Name); ExtractField(node, field, ref classObject); } Log ("========== Parsed object " + classObject.GetType ().Name + " ======================"); return classObject; } IList ExtractList(JSONNode node, IList listObject) { Log ("========== Parsing list " + listObject.GetType ().Name + " ====================="); Type listType = listObject.GetType().GetGenericArguments()[0]; foreach (JSONNode item in node.AsArray.Childs) { listObject.Add(ExtractItem(item, listType)); } return listObject; Log ("========== Parsed list " + listObject.GetType ().Name + " ======================"); } public static bool IsNumericTypeNullable(Type t) { return IsNumericType (Type.GetTypeCode (t)) || IsNumericType (Type.GetTypeCode(Nullable.GetUnderlyingType (t))); } public static bool IsNumericType(TypeCode tc) { switch (tc) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Single: return true; default: return false; } } } }
/* 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.Linq; using System.Text; namespace Orleans { internal static class SetExtensions { /// <summary> /// Shortcut to create HashSet from IEnumerable that supports type inference /// (which the standard constructor does not) /// </summary> /// <typeparam name="TK"></typeparam> /// <typeparam name="TV"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public static HashSet<T> ToSet<T>(this IEnumerable<T> values) { if (values == null) return null; return new HashSet<T>(values); } public static bool ListEquals<T>(this IList<T> a, IList<T> b) { if (a.Count != b.Count) return false; return new HashSet<T>(a).SetEquals(new HashSet<T>(b)); } public static bool IEnumerableEquals<T>(this IEnumerable<T> a, IEnumerable<T> b) { return new HashSet<T>(a).SetEquals(new HashSet<T>(b)); } public static bool IsSupersetOf<T>(this IEnumerable<T> a, IEnumerable<T> b) { return new HashSet<T>(a).IsSupersetOf(new HashSet<T>(b)); } /// <summary> /// Synchronize contents of two dictionaries with mutable values /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="a">Dictionary</param> /// <param name="b">Dictionary</param> /// <param name="copy">Return a copy of a value</param> /// <param name="sync">Synchronize two mutable values</param> private static void Synchronize<TKey, TValue>(this Dictionary<TKey, TValue> a, Dictionary<TKey, TValue> b, Func<TValue, TValue> copy, Action<TValue, TValue> sync) { var akeys = a.Keys.ToSet(); var bkeys = b.Keys.ToSet(); var aonly = akeys.Except(bkeys).ToSet(); var bonly = bkeys.Except(akeys).ToSet(); var both = akeys.Intersect(bkeys).ToSet(); foreach (var ak in aonly) { b.Add(ak, copy(a[ak])); } foreach (var bk in bonly) { a.Add(bk, copy(b[bk])); } foreach (var k in both) { sync(a[k], b[k]); } } /// <summary> /// Synchronize contents of two dictionaries with immutable values /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="a">Dictionary</param> /// <param name="b">Dictionary</param> /// <param name="sync">Synchronize two values, return synced value</param> private static void Synchronize<TKey, TValue>(this Dictionary<TKey, TValue> a, Dictionary<TKey, TValue> b, Func<TValue, TValue, TValue> sync) { var akeys = a.Keys.ToSet(); var bkeys = b.Keys.ToSet(); var aonly = akeys.Except(bkeys).ToSet(); var bonly = bkeys.Except(akeys).ToSet(); var both = akeys.Intersect(bkeys).ToSet(); foreach (var ak in aonly) { b.Add(ak, a[ak]); } foreach (var bk in bonly) { a.Add(bk, b[bk]); } foreach (var k in both) { var s = sync(a[k], b[k]); a[k] = s; b[k] = s; } } /// <summary> /// Synchronize contents of two nested dictionaries with mutable values /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TKey2">Nested key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="a">Dictionary</param> /// <param name="b">Dictionary</param> /// <param name="copy">Return a copy of a value</param> /// <param name="sync">Synchronize two mutable values</param> private static void Synchronize2<TKey, TKey2, TValue>(this Dictionary<TKey, Dictionary<TKey2, TValue>> a, Dictionary<TKey, Dictionary<TKey2, TValue>> b, Func<TValue, TValue> copy, Action<TValue, TValue> sync) { a.Synchronize(b, d => d.Copy(copy), (d1, d2) => d1.Synchronize(d2, copy, sync)); } /// <summary> /// Synchronize contents of two nested dictionaries with immutable values /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TKey2">Nested key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="a">Dictionary</param> /// <param name="b">Dictionary</param> /// <param name="copy">Return a copy of a value</param> /// <param name="sync">Synchronize two immutable values</param> private static void Synchronize2<TKey, TKey2, TValue>(this Dictionary<TKey, Dictionary<TKey2, TValue>> a, Dictionary<TKey, Dictionary<TKey2, TValue>> b, Func<TValue, TValue, TValue> sync) { a.Synchronize(b, d => new Dictionary<TKey2, TValue>(d), (d1, d2) => d1.Synchronize(d2, sync)); } public static Dictionary<TKey, TValue> Copy<TKey, TValue>(this Dictionary<TKey, TValue> original) { return new Dictionary<TKey, TValue>(original); } /// <summary> /// Copy a dictionary with mutable values /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="original"></param> /// <param name="copy"></param> /// <returns></returns> private static Dictionary<TKey, TValue> Copy<TKey, TValue>(this Dictionary<TKey, TValue> original, Func<TValue, TValue> copy) { return original.ToDictionary(pair => pair.Key, pair => copy(pair.Value)); } /// <summary> /// ToString every element of an enumeration /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="toString">Can supply null to use Object.ToString()</param> /// <param name="before">Before each element, or space if unspecified</param> /// <returns></returns> public static string ToStrings<T>(this IEnumerable<T> list, Func<T, object> toString = null, string separator = " ") { if (list == null) return ""; toString = toString ?? (x => x); //Func<T, string> toStringPrinter = (x => // { // object obj = toString(x); // if(obj != null) // return obj.ToString(); // else // return "null"; // }); //return Utils.IEnumerableToString(list, toStringPrinter, separator); //Do NOT use Aggregate for string concatenation. It is very inefficient, will reallocate and copy lots of intermediate strings. //toString = toString ?? (x => x); return list.Aggregate("", (s, x) => s + separator + toString(x)); } public static List<T> Union<T>(List<T> list1, List<T> list2) { if (list1 == null && list2 == null) return null; if (list1 == null) return list2; if (list2 == null) return list1; list1.AddRange(list2); return list1; } } }
using System; using System.Collections.Generic; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace Xtricate.Dynamic { /// <summary> /// Creates a serializable string/object dictionary that is XML serializable /// Encodes keys as element names and values as simple values with a type /// attribute that contains an XML type name. Complex names encode the type /// name with type='___namespace.classname' format followed by a standard xml /// serialized format. The latter serialization can be slow so it's not recommended /// to pass complex types if performance is critical. /// </summary> [XmlRoot("properties")] public class PropertyBag : PropertyBag<object> { /// <summary> /// Creates an instance of a propertybag from an Xml string /// </summary> /// <param name="xml">Serialize</param> /// <returns></returns> public static new PropertyBag CreateFromXml(string xml) { var bag = new PropertyBag(); bag.FromXml(xml); return bag; } } /// <summary> /// Creates a serializable string for generic types that is XML serializable. /// Encodes keys as element names and values as simple values with a type /// attribute that contains an XML type name. Complex names encode the type /// name with type='___namespace.classname' format followed by a standard xml /// serialized format. The latter serialization can be slow so it's not recommended /// to pass complex types if performance is critical. /// </summary> /// <typeparam name="TValue">Must be a reference type. For value types use type object</typeparam> [XmlRoot("properties")] public class PropertyBag<TValue> : Dictionary<string, TValue>, IXmlSerializable { /// <summary> /// Not implemented - this means no schema information is passed /// so this won't work with ASMX/WCF services. /// </summary> /// <returns></returns> public XmlSchema GetSchema() { return null; } /// <summary> /// Serializes the dictionary to XML. Keys are /// serialized to element names and values as /// element values. An xml type attribute is embedded /// for each serialized element - a .NET type /// element is embedded for each complex type and /// prefixed with three underscores. /// </summary> /// <param name="writer"></param> public void WriteXml(XmlWriter writer) { foreach (var key in Keys) { var value = this[key]; Type type = null; if (value != null) type = value.GetType(); writer.WriteStartElement("item"); writer.WriteStartElement("key"); writer.WriteString(key); writer.WriteEndElement(); writer.WriteStartElement("value"); var xmlType = Utilities.MapTypeToXmlType(type); var isCustom = false; // Type information attribute if not string if (value == null) { writer.WriteAttributeString("type", "nil"); } else if (!string.IsNullOrEmpty(xmlType)) { if (xmlType != "string") { writer.WriteStartAttribute("type"); writer.WriteString(xmlType); writer.WriteEndAttribute(); } } else { isCustom = true; xmlType = "___" + value.GetType().FullName; writer.WriteStartAttribute("type"); writer.WriteString(xmlType); writer.WriteEndAttribute(); } // Serialize simple types with WriteValue if (!isCustom) { if (value != null) writer.WriteValue(value); } else { // Complex types require custom XmlSerializer var ser = new XmlSerializer(value.GetType()); ser.Serialize(writer, value); } writer.WriteEndElement(); // value writer.WriteEndElement(); // item } } /// <summary> /// Reads the custom serialized format /// </summary> /// <param name="reader"></param> public void ReadXml(XmlReader reader) { Clear(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "key") { string xmlType = null; var name = reader.ReadElementContentAsString(); // item element reader.ReadToNextSibling("value"); if (reader.MoveToNextAttribute()) xmlType = reader.Value; if (string.IsNullOrEmpty(xmlType)) xmlType = "string"; reader.MoveToContent(); TValue value; var strval = string.Empty; if (xmlType == "nil") value = default(TValue); // null // .NET types that don't map to XML we have to manually // deserialize else if (xmlType.StartsWith("___")) { // skip ahead to serialized value element while (reader.Read() && reader.NodeType != XmlNodeType.Element) { } var type = Utilities.GetTypeFromName(xmlType.Substring(3)); var ser = new XmlSerializer(type); value = (TValue) ser.Deserialize(reader); } else value = (TValue) reader.ReadElementContentAs(Utilities.MapXmlTypeToType(xmlType), null); Add(name, value); } } } /// <summary> /// Serializes this dictionary to an XML string /// </summary> /// <returns>XML String or Null if it fails</returns> public string ToXml() { string xml = null; SerializationHelper.SerializeObject(this, out xml); return xml; } /// <summary> /// Deserializes from an XML string /// </summary> /// <param name="xml"></param> /// <returns>true or false</returns> public bool FromXml(string xml) { Clear(); // if xml string is empty we return an empty dictionary if (string.IsNullOrEmpty(xml)) return true; var result = SerializationHelper.DeSerializeObject(xml, GetType()) as PropertyBag<TValue>; if (result != null) { foreach (var item in result) { Add(item.Key, item.Value); } } else // null is a failure return false; return true; } /// <summary> /// Creates an instance of a propertybag from an Xml string /// </summary> /// <param name="xml"></param> /// <returns></returns> public static PropertyBag<TValue> CreateFromXml(string xml) { var bag = new PropertyBag<TValue>(); bag.FromXml(xml); return bag; } } internal static class Utilities { /// <summary> /// Helper routine that looks up a type name and tries to retrieve the /// full type reference in the actively executing assemblies. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static Type GetTypeFromName(string typeName) { Type type = null; // try to find manually foreach (var ass in AppDomain.CurrentDomain.GetAssemblies()) { type = ass.GetType(typeName, false); if (type != null) break; } return type; } /// <summary> /// Converts a .NET type into an XML compatible type - roughly /// </summary> /// <param name="type"></param> /// <returns></returns> public static string MapTypeToXmlType(Type type) { if (type == typeof (string) || type == typeof (char)) return "string"; if (type == typeof (int) || type == typeof (int)) return "integer"; if (type == typeof (long) || type == typeof (long)) return "long"; if (type == typeof (bool)) return "boolean"; if (type == typeof (DateTime)) return "datetime"; if (type == typeof (float)) return "float"; if (type == typeof (decimal)) return "decimal"; if (type == typeof (double)) return "double"; if (type == typeof (float)) return "single"; if (type == typeof (byte)) return "byte"; if (type == typeof (byte[])) return "base64Binary"; return null; } public static Type MapXmlTypeToType(string xmlType) { xmlType = xmlType.ToLower(); if (xmlType == "string") return typeof (string); if (xmlType == "integer") return typeof (int); if (xmlType == "long") return typeof (long); if (xmlType == "boolean") return typeof (bool); if (xmlType == "datetime") return typeof (DateTime); if (xmlType == "float") return typeof (float); if (xmlType == "decimal") return typeof (decimal); if (xmlType == "double") return typeof (double); if (xmlType == "single") return typeof (float); if (xmlType == "byte") return typeof (byte); if (xmlType == "base64binary") return typeof (byte[]); // return null if no match is found // don't throw so the caller can decide more efficiently what to do // with this error result return null; } } }
using EIDSS.Reports.Parameterized.Human.AJ.DataSets; using EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSetTableAdapters; using EIDSS.Reports.Parameterized.Human.GG.DataSet; using EIDSS.Reports.Parameterized.Human.GG.Report; namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { partial class AssignmentLabDiagnosticReport { #region 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AssignmentLabDiagnosticReport)); this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.Detail1 = new DevExpress.XtraReports.UI.DetailBand(); this.ReportDetailTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow(); this.SampleTypeCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SampleIDCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SampleCollectionDateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SampleSentDateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.ReportDetailHeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.SecondReportHeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderPatientNameCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderSexCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderDOBCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderAgeCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderAddressCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderDiagnosisCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.ReportHeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell333 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderCaseIDBarcodeCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderCaseIDCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderOrganizationNameCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell(); this.FooterDoctorsNameCell = new DevExpress.XtraReports.UI.XRTableCell(); this.m_Adapter = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSetTableAdapters.AssignmentDiagnosticAdapter(); this.m_DataSet = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSet(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ReportDetailTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ReportDetailHeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SecondReportHeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ReportHeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.Multiline = true; this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; this.PageHeader.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.PageHeader, "PageHeader"); // // PageFooter // this.PageFooter.StylePriority.UseBorders = false; resources.ApplyResources(this.PageFooter, "PageFooter"); // // ReportHeader // resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.StylePriority.UseFont = false; // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // DetailReport // this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail1, this.ReportHeader1, this.ReportFooter}); this.DetailReport.DataAdapter = this.m_Adapter; this.DetailReport.DataMember = "AssignmentDiagnostic"; this.DetailReport.DataSource = this.m_DataSet; this.DetailReport.Level = 0; this.DetailReport.Name = "DetailReport"; this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); // // Detail1 // this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.ReportDetailTable}); resources.ApplyResources(this.Detail1, "Detail1"); this.Detail1.Name = "Detail1"; // // ReportDetailTable // this.ReportDetailTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.ReportDetailTable, "ReportDetailTable"); this.ReportDetailTable.Name = "ReportDetailTable"; this.ReportDetailTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow9}); this.ReportDetailTable.StylePriority.UseBorders = false; this.ReportDetailTable.StylePriority.UseFont = false; // // xrTableRow9 // this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.SampleTypeCell, this.SampleIDCell, this.SampleCollectionDateCell, this.SampleSentDateCell}); this.xrTableRow9.Name = "xrTableRow9"; resources.ApplyResources(this.xrTableRow9, "xrTableRow9"); // // SampleTypeCell // this.SampleTypeCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strSampleType")}); this.SampleTypeCell.Name = "SampleTypeCell"; resources.ApplyResources(this.SampleTypeCell, "SampleTypeCell"); // // SampleIDCell // this.SampleIDCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strSampleId")}); this.SampleIDCell.Name = "SampleIDCell"; resources.ApplyResources(this.SampleIDCell, "SampleIDCell"); // // SampleCollectionDateCell // this.SampleCollectionDateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.datSampleCollectedDate", "{0:dd/MM/yyyy}")}); this.SampleCollectionDateCell.Name = "SampleCollectionDateCell"; resources.ApplyResources(this.SampleCollectionDateCell, "SampleCollectionDateCell"); // // SampleSentDateCell // this.SampleSentDateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.datSampleSentDate", "{0:dd/MM/yyyy}")}); this.SampleSentDateCell.Name = "SampleSentDateCell"; resources.ApplyResources(this.SampleSentDateCell, "SampleSentDateCell"); // // ReportHeader1 // this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.ReportDetailHeaderTable, this.SecondReportHeaderTable, this.ReportHeaderTable}); resources.ApplyResources(this.ReportHeader1, "ReportHeader1"); this.ReportHeader1.Name = "ReportHeader1"; this.ReportHeader1.StylePriority.UseFont = false; this.ReportHeader1.StylePriority.UseTextAlignment = false; // // ReportDetailHeaderTable // this.ReportDetailHeaderTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.ReportDetailHeaderTable, "ReportDetailHeaderTable"); this.ReportDetailHeaderTable.Name = "ReportDetailHeaderTable"; this.ReportDetailHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow15}); this.ReportDetailHeaderTable.StylePriority.UseBorders = false; this.ReportDetailHeaderTable.StylePriority.UseFont = false; this.ReportDetailHeaderTable.StylePriority.UseTextAlignment = false; // // xrTableRow15 // this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell33, this.xrTableCell34, this.xrTableCell16, this.xrTableCell11}); this.xrTableRow15.Name = "xrTableRow15"; resources.ApplyResources(this.xrTableRow15, "xrTableRow15"); // // xrTableCell33 // this.xrTableCell33.Name = "xrTableCell33"; resources.ApplyResources(this.xrTableCell33, "xrTableCell33"); // // xrTableCell34 // this.xrTableCell34.Name = "xrTableCell34"; resources.ApplyResources(this.xrTableCell34, "xrTableCell34"); // // xrTableCell16 // this.xrTableCell16.Multiline = true; this.xrTableCell16.Name = "xrTableCell16"; resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); // // xrTableCell11 // this.xrTableCell11.Multiline = true; this.xrTableCell11.Name = "xrTableCell11"; resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); // // SecondReportHeaderTable // resources.ApplyResources(this.SecondReportHeaderTable, "SecondReportHeaderTable"); this.SecondReportHeaderTable.Name = "SecondReportHeaderTable"; this.SecondReportHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow12, this.xrTableRow10, this.xrTableRow11, this.xrTableRow13, this.xrTableRow14, this.xrTableRow17}); // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell18, this.xrTableCell19, this.xrTableCell20}); this.xrTableRow12.Name = "xrTableRow12"; resources.ApplyResources(this.xrTableRow12, "xrTableRow12"); // // xrTableCell18 // this.xrTableCell18.Name = "xrTableCell18"; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); // // xrTableCell19 // this.xrTableCell19.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); // // xrTableCell20 // this.xrTableCell20.Name = "xrTableCell20"; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); // // xrTableRow10 // this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell14, this.HeaderPatientNameCell, this.xrTableCell15, this.HeaderSexCell}); this.xrTableRow10.Name = "xrTableRow10"; resources.ApplyResources(this.xrTableRow10, "xrTableRow10"); // // xrTableCell14 // this.xrTableCell14.Name = "xrTableCell14"; resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); // // HeaderPatientNameCell // this.HeaderPatientNameCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.HeaderPatientNameCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strPatientName")}); this.HeaderPatientNameCell.Name = "HeaderPatientNameCell"; this.HeaderPatientNameCell.StylePriority.UseBorders = false; resources.ApplyResources(this.HeaderPatientNameCell, "HeaderPatientNameCell"); // // xrTableCell15 // this.xrTableCell15.Name = "xrTableCell15"; this.xrTableCell15.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); // // HeaderSexCell // this.HeaderSexCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.HeaderSexCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strSex")}); this.HeaderSexCell.Name = "HeaderSexCell"; this.HeaderSexCell.StylePriority.UseBorders = false; resources.ApplyResources(this.HeaderSexCell, "HeaderSexCell"); // // xrTableRow11 // this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell21, this.HeaderDOBCell, this.xrTableCell23, this.HeaderAgeCell}); this.xrTableRow11.Name = "xrTableRow11"; resources.ApplyResources(this.xrTableRow11, "xrTableRow11"); // // xrTableCell21 // this.xrTableCell21.Name = "xrTableCell21"; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); // // HeaderDOBCell // this.HeaderDOBCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.HeaderDOBCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.datDateOfBirth", "{0:dd/MM/yyyy}")}); this.HeaderDOBCell.Name = "HeaderDOBCell"; this.HeaderDOBCell.StylePriority.UseBorders = false; resources.ApplyResources(this.HeaderDOBCell, "HeaderDOBCell"); // // xrTableCell23 // this.xrTableCell23.Name = "xrTableCell23"; this.xrTableCell23.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); // // HeaderAgeCell // this.HeaderAgeCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.HeaderAgeCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strAge")}); this.HeaderAgeCell.Name = "HeaderAgeCell"; this.HeaderAgeCell.StylePriority.UseBorders = false; resources.ApplyResources(this.HeaderAgeCell, "HeaderAgeCell"); // // xrTableRow13 // this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell25, this.HeaderAddressCell}); this.xrTableRow13.Name = "xrTableRow13"; resources.ApplyResources(this.xrTableRow13, "xrTableRow13"); // // xrTableCell25 // this.xrTableCell25.Name = "xrTableCell25"; resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); // // HeaderAddressCell // this.HeaderAddressCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.HeaderAddressCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strAddress")}); this.HeaderAddressCell.Name = "HeaderAddressCell"; this.HeaderAddressCell.StylePriority.UseBorders = false; resources.ApplyResources(this.HeaderAddressCell, "HeaderAddressCell"); // // xrTableRow14 // this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell27, this.HeaderDiagnosisCell}); this.xrTableRow14.Name = "xrTableRow14"; resources.ApplyResources(this.xrTableRow14, "xrTableRow14"); // // xrTableCell27 // this.xrTableCell27.Name = "xrTableCell27"; resources.ApplyResources(this.xrTableCell27, "xrTableCell27"); // // HeaderDiagnosisCell // this.HeaderDiagnosisCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.HeaderDiagnosisCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strDiagnosis")}); this.HeaderDiagnosisCell.Name = "HeaderDiagnosisCell"; this.HeaderDiagnosisCell.StylePriority.UseBorders = false; resources.ApplyResources(this.HeaderDiagnosisCell, "HeaderDiagnosisCell"); // // xrTableRow17 // this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1, this.xrTableCell10}); this.xrTableRow17.Name = "xrTableRow17"; resources.ApplyResources(this.xrTableRow17, "xrTableRow17"); // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); // // xrTableCell10 // this.xrTableCell10.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // ReportHeaderTable // resources.ApplyResources(this.ReportHeaderTable, "ReportHeaderTable"); this.ReportHeaderTable.Name = "ReportHeaderTable"; this.ReportHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow4, this.xrTableRow2, this.xrTableRow3, this.xrTableRow5, this.xrTableRow6, this.xrTableRow7, this.xrTableRow8}); this.ReportHeaderTable.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell333, this.xrTableCell3}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // xrTableCell333 // this.xrTableCell333.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTableCell333, "xrTableCell333"); this.xrTableCell333.Name = "xrTableCell333"; this.xrTableCell333.StylePriority.UseBorders = false; this.xrTableCell333.StylePriority.UseFont = false; // // xrTableCell3 // this.xrTableCell3.Name = "xrTableCell3"; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.xrTableCell6}); this.xrTableRow4.Name = "xrTableRow4"; this.xrTableRow4.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); // // xrTableCell5 // this.xrTableCell5.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // xrTableCell6 // this.xrTableCell6.Name = "xrTableCell6"; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderCaseIDBarcodeCell, this.xrTableCell4}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // HeaderCaseIDBarcodeCell // resources.ApplyResources(this.HeaderCaseIDBarcodeCell, "HeaderCaseIDBarcodeCell"); this.HeaderCaseIDBarcodeCell.Name = "HeaderCaseIDBarcodeCell"; this.HeaderCaseIDBarcodeCell.StylePriority.UseFont = false; // // xrTableCell4 // this.xrTableCell4.Name = "xrTableCell4"; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderCaseIDCell, this.xrTableCell2}); this.xrTableRow3.Name = "xrTableRow3"; resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); // // HeaderCaseIDCell // this.HeaderCaseIDCell.Name = "HeaderCaseIDCell"; this.HeaderCaseIDCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.HeaderCaseIDCell, "HeaderCaseIDCell"); // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell7, this.xrTableCell8}); this.xrTableRow5.Name = "xrTableRow5"; resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); // // xrTableCell7 // resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.StylePriority.UseFont = false; this.xrTableCell7.StylePriority.UseTextAlignment = false; // // xrTableCell8 // this.xrTableCell8.Name = "xrTableCell8"; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); // // xrTableRow6 // this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderOrganizationNameCell}); this.xrTableRow6.Name = "xrTableRow6"; resources.ApplyResources(this.xrTableRow6, "xrTableRow6"); // // HeaderOrganizationNameCell // this.HeaderOrganizationNameCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.HeaderOrganizationNameCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strReceivedOrganizationNameAddress")}); resources.ApplyResources(this.HeaderOrganizationNameCell, "HeaderOrganizationNameCell"); this.HeaderOrganizationNameCell.Name = "HeaderOrganizationNameCell"; this.HeaderOrganizationNameCell.StylePriority.UseBorders = false; this.HeaderOrganizationNameCell.StylePriority.UseFont = false; this.HeaderOrganizationNameCell.StylePriority.UseTextAlignment = false; // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell12}); this.xrTableRow7.Name = "xrTableRow7"; resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); // // xrTableCell12 // this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell9}); this.xrTableRow8.Name = "xrTableRow8"; resources.ApplyResources(this.xrTableRow8, "xrTableRow8"); // // xrTableCell9 // resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.StylePriority.UseFont = false; // // ReportFooter // this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; this.ReportFooter.StylePriority.UseTextAlignment = false; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow16}); // // xrTableRow16 // this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell40, this.FooterDoctorsNameCell}); this.xrTableRow16.Name = "xrTableRow16"; resources.ApplyResources(this.xrTableRow16, "xrTableRow16"); // // xrTableCell40 // this.xrTableCell40.Name = "xrTableCell40"; resources.ApplyResources(this.xrTableCell40, "xrTableCell40"); // // FooterDoctorsNameCell // this.FooterDoctorsNameCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.FooterDoctorsNameCell.Name = "FooterDoctorsNameCell"; this.FooterDoctorsNameCell.StylePriority.UseBorders = false; resources.ApplyResources(this.FooterDoctorsNameCell, "FooterDoctorsNameCell"); // // m_Adapter // this.m_Adapter.ClearBeforeFill = true; // // m_DataSet // this.m_DataSet.DataSetName = "AntibioticResistanceCardDataSet"; this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // AssignmentLabDiagnosticReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.DetailReport}); resources.ApplyResources(this, "$this"); this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.Version = "14.1"; this.Controls.SetChildIndex(this.DetailReport, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ReportDetailTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ReportDetailHeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SecondReportHeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ReportHeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand DetailReport; private DevExpress.XtraReports.UI.DetailBand Detail1; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader1; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private AssignmentDiagnosticAdapter m_Adapter; private AssignmentLabDiagnosticDataSet m_DataSet; private DevExpress.XtraReports.UI.XRTable ReportHeaderTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell HeaderCaseIDBarcodeCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell333; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell HeaderCaseIDCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableRow xrTableRow6; private DevExpress.XtraReports.UI.XRTableCell HeaderOrganizationNameCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTable ReportDetailTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow9; private DevExpress.XtraReports.UI.XRTableCell SampleIDCell; private DevExpress.XtraReports.UI.XRTableCell SampleTypeCell; private DevExpress.XtraReports.UI.XRTable ReportDetailHeaderTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell33; private DevExpress.XtraReports.UI.XRTableCell xrTableCell34; private DevExpress.XtraReports.UI.XRTable SecondReportHeaderTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableRow xrTableRow10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell HeaderPatientNameCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell HeaderSexCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell HeaderDOBCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableCell HeaderAgeCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableCell HeaderAddressCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell27; private DevExpress.XtraReports.UI.XRTableCell HeaderDiagnosisCell; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell40; private DevExpress.XtraReports.UI.XRTableCell FooterDoctorsNameCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell SampleCollectionDateCell; private DevExpress.XtraReports.UI.XRTableCell SampleSentDateCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; } }
// // CodeGenerationPanel.cs: Code generation panel to configure project // // Authors: // Marcos David Marin Amador <[email protected]> // // Copyright (C) 2007 Marcos David Marin Amador // // // This source code is licenced under The 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 MonoDevelop.Core; using MonoDevelop.Ide.Gui.Dialogs; using MonoDevelop.Components; using MonoDevelop.Ide; namespace CBinding { public partial class CodeGenerationPanel : Gtk.Bin { private CProjectConfiguration configuration; private Gtk.ListStore libStore = new Gtk.ListStore (typeof(string)); private Gtk.ListStore libPathStore = new Gtk.ListStore (typeof(string)); private Gtk.ListStore includePathStore = new Gtk.ListStore (typeof(string)); static string[,] quickPathInsertMenu = new string[,] { {GettextCatalog.GetString ("_Project Directory"), "${ProjectDir}"}, {GettextCatalog.GetString ("_Root Solution Directory"), "${CombineDir}"}, }; public CodeGenerationPanel () { this.Build (); Gtk.CellRendererText textRenderer = new Gtk.CellRendererText (); libTreeView.Model = libStore; libTreeView.HeadersVisible = false; libTreeView.AppendColumn ("Library", textRenderer, "text", 0); libPathTreeView.Model = libPathStore; libPathTreeView.HeadersVisible = false; libPathTreeView.AppendColumn ("Library", textRenderer, "text", 0); includePathTreeView.Model = includePathStore; includePathTreeView.HeadersVisible = false; includePathTreeView.AppendColumn ("Include", textRenderer, "text", 0); new MenuButtonEntry (libPathEntry, quickInsertLibButton, quickPathInsertMenu); new MenuButtonEntry (includePathEntry, quickInsertIncludeButton, quickPathInsertMenu); } public void Load (CProjectConfiguration config) { configuration = config; switch (configuration.WarningLevel) { case WarningLevel.None: noWarningRadio.Active = true; break; case WarningLevel.Normal: normalWarningRadio.Active = true; break; case WarningLevel.All: allWarningRadio.Active = true; break; } warningsAsErrorsCheckBox.Active = configuration.WarningsAsErrors; optimizationSpinButton.Value = configuration.OptimizationLevel; switch (configuration.CompileTarget) { case CBinding.CompileTarget.Bin: targetComboBox.Active = 0; break; case CBinding.CompileTarget.StaticLibrary: targetComboBox.Active = 1; break; case CBinding.CompileTarget.SharedLibrary: targetComboBox.Active = 2; break; } extraCompilerTextView.Buffer.Text = configuration.ExtraCompilerArguments; extraLinkerTextView.Buffer.Text = configuration.ExtraLinkerArguments; defineSymbolsTextEntry.Text = configuration.DefineSymbols; libStore.Clear (); foreach (string lib in configuration.Libs) libStore.AppendValues (lib); libPathStore.Clear (); foreach (string libPath in configuration.LibPaths) libPathStore.AppendValues (libPath); includePathStore.Clear (); foreach (string includePath in configuration.Includes) includePathStore.AppendValues (includePath); } private void OnIncludePathAdded (object sender, EventArgs e) { if (includePathEntry.Text.Length > 0) { includePathStore.AppendValues (includePathEntry.Text); includePathEntry.Text = string.Empty; } } private void OnIncludePathRemoved (object sender, EventArgs e) { Gtk.TreeIter iter; includePathTreeView.Selection.GetSelected (out iter); includePathStore.Remove (ref iter); } private void OnLibPathAdded (object sender, EventArgs e) { if (libPathEntry.Text.Length > 0) { libPathStore.AppendValues (libPathEntry.Text); libPathEntry.Text = string.Empty; } } private void OnLibPathRemoved (object sender, EventArgs e) { Gtk.TreeIter iter; libPathTreeView.Selection.GetSelected (out iter); libPathStore.Remove (ref iter); } private void OnLibAdded (object sender, EventArgs e) { if (libAddEntry.Text.Length > 0) { libStore.AppendValues (libAddEntry.Text); libAddEntry.Text = string.Empty; } } private void OnLibRemoved (object sender, EventArgs e) { Gtk.TreeIter iter; libTreeView.Selection.GetSelected (out iter); libStore.Remove (ref iter); } // TODO: This is platform specific... the C Binding should have a global list of 'standard' library dirs... internal const string DEFAULT_LIB_DIR = "/usr/lib"; internal const string DEFAULT_INCLUDE_DIR = "/usr/lib"; internal const string STATIC_LIB_FILTER = "*.a"; internal const string DYNAMIC_LIB_FILTER = "*.so"; private void OnBrowseButtonClick (object sender, EventArgs e) { var dialog = new MonoDevelop.Components.SelectFileDialog (GettextCatalog.GetString ("Add Library")) { TransientFor = (Gtk.Window) Toplevel, CurrentFolder = DEFAULT_LIB_DIR, }; dialog.AddFilter (GettextCatalog.GetString ("Static Library"), STATIC_LIB_FILTER); dialog.AddFilter (GettextCatalog.GetString ("Dynamic Library"), DYNAMIC_LIB_FILTER); dialog.AddAllFilesFilter (); if (dialog.Run ()) libAddEntry.Text = dialog.SelectedFile; } private void OnIncludePathBrowseButtonClick (object sender, EventArgs e) { var dialog = new MonoDevelop.Components.SelectFolderDialog (GettextCatalog.GetString ("Add Path")) { TransientFor = (Gtk.Window) Toplevel, CurrentFolder = DEFAULT_INCLUDE_DIR, }; if (dialog.Run ()) includePathEntry.Text = dialog.SelectedFile; } private void OnLibPathBrowseButtonClick (object sender, EventArgs e) { var dialog = new MonoDevelop.Components.SelectFolderDialog (GettextCatalog.GetString ("Add Path")) { TransientFor = (Gtk.Window) Toplevel, CurrentFolder = DEFAULT_LIB_DIR, }; if (dialog.Run ()) libPathEntry.Text = dialog.SelectedFile; } public bool Store () { if (configuration == null) return false; string line; Gtk.TreeIter iter; if (noWarningRadio.Active) configuration.WarningLevel = WarningLevel.None; else if (normalWarningRadio.Active) configuration.WarningLevel = WarningLevel.Normal; else configuration.WarningLevel = WarningLevel.All; configuration.WarningsAsErrors = warningsAsErrorsCheckBox.Active; configuration.OptimizationLevel = (int)optimizationSpinButton.Value; switch (targetComboBox.ActiveText) { case "Executable": configuration.CompileTarget = CBinding.CompileTarget.Bin; break; case "Static Library": configuration.CompileTarget = CBinding.CompileTarget.StaticLibrary; break; case "Shared Object": configuration.CompileTarget = CBinding.CompileTarget.SharedLibrary; break; } configuration.ExtraCompilerArguments = extraCompilerTextView.Buffer.Text; configuration.ExtraLinkerArguments = extraLinkerTextView.Buffer.Text; configuration.DefineSymbols = defineSymbolsTextEntry.Text; libStore.GetIterFirst (out iter); configuration.Libs.Clear (); while (libStore.IterIsValid (iter)) { line = (string)libStore.GetValue (iter, 0); configuration.Libs.Add (line); libStore.IterNext (ref iter); } libPathStore.GetIterFirst (out iter); configuration.LibPaths.Clear (); while (libPathStore.IterIsValid (iter)) { line = (string)libPathStore.GetValue (iter, 0); configuration.LibPaths.Add (line); libPathStore.IterNext (ref iter); } includePathStore.GetIterFirst (out iter); configuration.Includes.Clear (); while (includePathStore.IterIsValid (iter)) { line = (string)includePathStore.GetValue (iter, 0); configuration.Includes.Add (line); includePathStore.IterNext (ref iter); } return true; } protected virtual void OnLibAddEntryChanged (object sender, EventArgs e) { if (string.IsNullOrEmpty (libAddEntry.Text)) addLibButton.Sensitive = false; else addLibButton.Sensitive = true; } protected virtual void OnLibTreeViewCursorChanged (object sender, System.EventArgs e) { removeLibButton.Sensitive = true; } protected virtual void OnRemoveLibButtonClicked (object sender, System.EventArgs e) { removeLibButton.Sensitive = false; } protected virtual void OnIncludePathEntryChanged (object sender, System.EventArgs e) { if (string.IsNullOrEmpty (includePathEntry.Text)) includePathAddButton.Sensitive = false; else includePathAddButton.Sensitive = true; } protected virtual void OnLibPathEntryChanged (object sender, System.EventArgs e) { if (string.IsNullOrEmpty (libPathEntry.Text)) libPathAddButton.Sensitive = false; else libPathAddButton.Sensitive = true; } protected virtual void OnIncludePathTreeViewCursorChanged (object sender, System.EventArgs e) { includePathRemoveButton.Sensitive = true; } protected virtual void OnIncludePathRemoveButtonClicked (object sender, System.EventArgs e) { includePathRemoveButton.Sensitive = false; } protected virtual void OnLibPathTreeViewCursorChanged (object sender, System.EventArgs e) { libPathRemoveButton.Sensitive = true; } protected virtual void OnLibPathRemoveButtonClicked (object sender, System.EventArgs e) { libPathRemoveButton.Sensitive = false; } protected virtual void OnLibAddEntryActivated (object sender, System.EventArgs e) { OnLibAdded (this, new EventArgs ()); } protected virtual void OnIncludePathEntryActivated (object sender, System.EventArgs e) { OnIncludePathAdded (this, new EventArgs ()); } protected virtual void OnLibPathEntryActivated (object sender, System.EventArgs e) { OnLibPathAdded (this, new EventArgs ()); } } public class CodeGenerationPanelBinding : MultiConfigItemOptionsPanel { private CodeGenerationPanel panel; public override Gtk.Widget CreatePanelWidget () { return panel = new CodeGenerationPanel (); } public override void LoadConfigData () { panel.Load ((CProjectConfiguration) CurrentConfiguration); } public override void ApplyChanges () { panel.Store (); } } }
using UnityEngine; using UnityEngine.Serialization; using System.Collections; using System.Collections.Generic; namespace UMA { /// <summary> /// Slot data contains mesh information and overlay references. /// </summary> [System.Serializable] #if !UMA2_LEAN_AND_CLEAN public partial class SlotData : System.IEquatable<SlotData> #else public class SlotData : System.IEquatable<SlotData> #endif { /// <summary> /// The asset contains the immutable portions of the slot. /// </summary> public SlotDataAsset asset; /// <summary> /// Adjusts the resolution of slot overlays. /// </summary> public float overlayScale = 1.0f; #if UMA2_LEAN_AND_CLEAN public string slotName { get { return asset.slotName; } } #endif /// <summary> /// list of overlays used to texture the slot. /// </summary> private List<OverlayData> overlayList = new List<OverlayData>(); /// <summary> /// Constructor for slot using the given asset. /// </summary> /// <param name="asset">Asset.</param> public SlotData(SlotDataAsset asset) { this.asset = asset; #if !UMA2_LEAN_AND_CLEAN slotName = asset.slotName; materialSample = asset.materialSample; #endif overlayScale = asset.overlayScale; } /// <summary> /// Deep copy of the SlotData. /// </summary> public SlotData Copy() { var res = new SlotData(asset); int overlayCount = overlayList.Count; res.overlayList = new List<OverlayData>(overlayCount); for (int i = 0; i < overlayCount; i++) { OverlayData overlay = overlayList[i]; if (overlay != null) { res.overlayList.Add(overlay.Duplicate()); } } return res; } public int GetTextureChannelCount(UMAGeneratorBase generator) { return asset.GetTextureChannelCount(generator); } public bool RemoveOverlay(params string[] names) { bool changed = false; foreach (var name in names) { for (int i = 0; i < overlayList.Count; i++) { if (overlayList[i].asset.overlayName == name) { overlayList.RemoveAt(i); changed = true; break; } } } return changed; } public bool SetOverlayColor(Color32 color, params string[] names) { bool changed = false; foreach (var name in names) { foreach (var overlay in overlayList) { if (overlay.asset.overlayName == name) { overlay.colorData.color = color; changed = true; } } } return changed; } public OverlayData GetOverlay(params string[] names) { foreach (var name in names) { foreach (var overlay in overlayList) { if (overlay.asset.overlayName == name) { return overlay; } } } return null; } public void SetOverlay(int index, OverlayData overlay) { if (index >= overlayList.Count) { overlayList.Capacity = index + 1; while (index >= overlayList.Count) { overlayList.Add(null); } } overlayList[index] = overlay; } public OverlayData GetOverlay(int index) { if (index < 0 || index >= overlayList.Count) return null; return overlayList[index]; } /// <summary> /// Attempts to find an equivalent overlay in the slot. /// </summary> /// <returns>The equivalent overlay (or null, if no equivalent).</returns> /// <param name="overlay">Overlay.</param> public OverlayData GetEquivalentOverlay(OverlayData overlay) { foreach (OverlayData overlay2 in overlayList) { if (OverlayData.Equivalent(overlay, overlay2)) { return overlay2; } } return null; } public int OverlayCount { get { return overlayList.Count; } } /// <summary> /// Sets the complete list of overlays. /// </summary> /// <param name="overlayList">The overlay list.</param> public void SetOverlayList(List<OverlayData> overlayList) { this.overlayList = overlayList; } /// <summary> /// Add an overlay to the slot. /// </summary> /// <param name="overlayData">Overlay.</param> public void AddOverlay(OverlayData overlayData) { if (overlayData) overlayList.Add(overlayData); } /// <summary> /// Gets the complete list of overlays. /// </summary> /// <returns>The overlay list.</returns> public List<OverlayData> GetOverlayList() { return overlayList; } internal bool Validate() { bool valid = true; if (asset.meshData != null) { if (asset.material == null) { Debug.LogError(string.Format("Slot '{0}' has a mesh but no material.", asset.slotName), asset); valid = false; } else { if (asset.material.material == null) { Debug.LogError(string.Format("Slot '{0}' has an umaMaterial without a material assigned.", asset.slotName), asset); valid = false; } else { for (int i = 0; i < asset.material.channels.Length; i++) { var channel = asset.material.channels[i]; if (!asset.material.material.HasProperty(channel.materialPropertyName)) { Debug.LogError(string.Format("Slot '{0}' Material Channel {1} refers to material property '{2}' but no such property exists.", asset.slotName, i, channel.materialPropertyName), asset); valid = false; } } } } for (int i = 0; i < overlayList.Count; i++) { var overlayData = overlayList[i]; if (overlayData != null) { if (overlayData.asset.material != asset.material) { Debug.LogError(string.Format("Slot '{0}' and Overlay '{1}' don't have the same UMA Material", asset.slotName, overlayData.asset.overlayName)); valid = false; } if ((overlayData.asset.textureList == null) || (overlayData.asset.textureList.Length != asset.material.channels.Length)) { Debug.LogError(string.Format("Overlay '{0}' doesn't have the right number of channels", overlayData.asset.overlayName)); valid = false; } else { for (int j = 0; j < asset.material.channels.Length; j++) { if ((overlayData.asset.textureList[j] == null) && (asset.material.channels[j].channelType != UMAMaterial.ChannelType.MaterialColor)) { Debug.LogError(string.Format("Overlay '{0}' missing required texture in channel {1}", overlayData.asset.overlayName, j)); valid = false; } } } if (overlayData.colorData.channelMask.Length < asset.material.channels.Length) { // Fixup colorData if moving from Legacy to PBR materials int oldsize = overlayData.colorData.channelMask.Length; System.Array.Resize (ref overlayData.colorData.channelMask, asset.material.channels.Length); System.Array.Resize (ref overlayData.colorData.channelAdditiveMask, asset.material.channels.Length); for (int j = oldsize; j > asset.material.channels.Length; j++) { overlayData.colorData.channelMask [j] = Color.white; overlayData.colorData.channelAdditiveMask [j] = Color.black; } Debug.LogWarning (string.Format ("Overlay '{0}' missing required color data on Asset: " + asset.name+" Resizing and adding defaults", overlayData.asset.overlayName)); } } } } else { #if !UMA2_LEAN_AND_CLEAN if (asset.meshRenderer != null) { Debug.LogError(string.Format("Slot '{0}' is a UMA 1x slot... you need to upgrade it by selecting it and using the UMA|Optimize Slot Meshes.", asset.slotName), asset); valid = false; } #endif if (asset.material != null) { for (int i = 0; i < asset.material.channels.Length; i++) { var channel = asset.material.channels[i]; if (!asset.material.material.HasProperty(channel.materialPropertyName)) { Debug.LogError(string.Format("Slot '{0}' Material Channel {1} refers to material property '{2}' but no such property exists.", asset.slotName, i, channel.materialPropertyName), asset); valid = false; } } } } return valid; } public override string ToString() { return "SlotData: " + asset.slotName; } #if !UMA2_LEAN_AND_CLEAN #region obsolete junk from version 1 [System.Obsolete("SlotData.materialSample is obsolete use asset.materialSample!", false)] public Material materialSample; [System.Obsolete("SlotData.slotName is obsolete use asset.slotName!", false)] public string slotName; [System.Obsolete("SlotData.listID is obsolete.", false)] public int listID = -1; [System.Obsolete("SlotData.meshRenderer is obsolete.", true)] public SkinnedMeshRenderer meshRenderer; [System.Obsolete("SlotData.boneNameHashes is obsolete.", true)] public int[] boneNameHashes; [System.Obsolete("SlotData.boneWeights is obsolete.", true)] public BoneWeight[] boneWeights; [System.Obsolete("SlotData.umaBoneData is obsolete.", true)] public Transform[] umaBoneData; [System.Obsolete("SlotData.animatedBones is obsolete, use SlotDataAsset.animatedBones.", true)] public Transform[] animatedBones = new Transform[0]; [System.Obsolete("SlotData.textureNameList is obsolete, use SlotDataAsset.textureNameList.", true)] public string[] textureNameList; [System.Obsolete("SlotData.slotDNA is obsolete, use SlotDataAsset.slotDNA.", true)] public DnaConverterBehaviour slotDNA; [System.Obsolete("SlotData.subMeshIndex is obsolete, use SlotDataAsset.subMeshIndex.", true)] public int subMeshIndex; /// <summary> /// Use this to identify slots that serves the same purpose /// Eg. ChestArmor, Helmet, etc. /// </summary> [System.Obsolete("SlotData.slotGroup is obsolete, use SlotDataAsset.slotGroup.", false)] public string slotGroup; /// <summary> /// Use this to identify what kind of overlays fit this slotData /// Eg. BaseMeshSkin, BaseMeshOverlays, GenericPlateArmor01 /// </summary> [System.Obsolete("SlotData.tags is obsolete, use SlotDataAsset.tags.", false)] public string[] tags; #endregion #endif #region operator ==, != and similar HACKS, seriously..... [System.Obsolete("You can no longer cast UnityEngine.Object to SlotData, perhaps you want to cast it into SlotDataAsset instead?", false)] public static implicit operator SlotData(UnityEngine.Object obj) { throw new System.NotImplementedException("You can no longer cast UnityEngine.Object to SlotData, perhaps you want to cast it into SlotDataAsset instead?"); } public static implicit operator bool(SlotData obj) { return ((System.Object)obj) != null && obj.asset != null; } public bool Equals(SlotData other) { return (this == other); } public override bool Equals(object other) { return Equals(other as SlotData); } public static bool operator ==(SlotData slot, SlotData obj) { if (slot) { if (obj) { return System.Object.ReferenceEquals(slot, obj); } return false; } return !((bool)obj); } public static bool operator !=(SlotData slot, SlotData obj) { if (slot) { if (obj) { return !System.Object.ReferenceEquals(slot, obj); } return true; } return ((bool)obj); } public override int GetHashCode() { return base.GetHashCode(); } #endregion } }
/*************************************************************************** * Feed.cs * * Copyright (C) 2007 Michael C. Urbanski * Written by Mike Urbanski <[email protected]> ****************************************************************************/ /* 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.IO; using System.Net; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Unix; using Hyena; using Hyena.Data.Sqlite; using Migo.Net; using Migo.TaskCore; using Migo.DownloadCore; namespace Migo.Syndication { public enum FeedAutoDownload : int { All = 0, One = 1, None = 2 } // TODO remove this, way too redundant with DownloadStatus public enum PodcastFeedActivity : int { Updating = 0, UpdatePending = 1, UpdateFailed = 2, ItemsDownloading = 4, ItemsQueued = 5, None = 6 } public class FeedProvider : MigoModelProvider<Feed> { public FeedProvider (HyenaSqliteConnection connection) : base (connection, "PodcastSyndications") { } protected override void CreateTable () { base.CreateTable (); CreateIndex ("PodcastSyndicationsIndex", "IsSubscribed, Title"); } protected override int ModelVersion { get { return 4; } } protected override void MigrateTable (int old_version) { CheckTable (); if (old_version < 2) { Connection.Execute (String.Format ("UPDATE {0} SET IsSubscribed=1", TableName)); } if (old_version < 3) { CreateIndex ("PodcastSyndicationsIndex", "IsSubscribed, Title"); } if (old_version < 4) { Connection.Execute (String.Format ("UPDATE {0} SET MaxItemCount=0 WHERE MaxItemCount=200", TableName)); } } } public class Feed : MigoItem<Feed> { private static FeedProvider provider; public static FeedProvider Provider { get { return provider; } } public static void Init () { provider = new FeedProvider (FeedsManager.Instance.Connection); } public static bool Exists (string url) { return Provider.Connection.Query<int> (String.Format ("select count(*) from {0} where url = ?", Provider.TableName), url) != 0; } //private bool canceled; //private bool deleted; //private bool updating; //private ManualResetEvent updatingHandle = new ManualResetEvent (true); private readonly object sync = new object (); private string copyright; private string description; private string image_url; private int update_period_minutes = 24 * 60; private string language; private DateTime last_build_date = DateTime.MinValue; private FeedDownloadError lastDownloadError; private DateTime last_download_time = DateTime.MinValue; private string link; //private string local_enclosure_path; private long dbid = -1; private long maxItemCount = 0; private DateTime pubDate; private FeedSyncSetting syncSetting; private string title; private string url; private string keywords, category; #region Database-bound Properties [DatabaseColumn ("FeedID", Constraints = DatabaseColumnConstraints.PrimaryKey)] public override long DbId { get { return dbid; } protected set { dbid = value; } } public static string UnknownPodcastTitle = Catalog.GetString ("Unknown Podcast"); [DatabaseColumn] public string Title { get { return title ?? UnknownPodcastTitle; } set { title = value; } } [DatabaseColumn] public string Description { get { return description; } set { description = value; } } [DatabaseColumn] public string Url { get { return url; } set { url = value; } } [DatabaseColumn] public string Keywords { get { return keywords; } set { keywords = value; } } [DatabaseColumn] public string Category { get { return category; } set { category = value; } } [DatabaseColumn] public string Copyright { get { return copyright; } set { copyright = value; } } [DatabaseColumn] public string ImageUrl { get { return image_url; } set { image_url = value; } } [DatabaseColumn] public int UpdatePeriodMinutes { get { return update_period_minutes; } set { update_period_minutes = value; } } [DatabaseColumn] public string Language { get { return language; } set { language = value; } } [DatabaseColumn] public FeedDownloadError LastDownloadError { get { return lastDownloadError; } set { lastDownloadError = value; } } [DatabaseColumn] public DateTime LastDownloadTime { get { return last_download_time; } set { last_download_time = value; } } [DatabaseColumn] public string Link { get { return link; } set { link = value; } } //[DatabaseColumn] public string LocalEnclosurePath { get { string escaped = Hyena.StringUtil.EscapeFilename (Title); return Path.Combine (FeedsManager.Instance.PodcastStorageDirectory, escaped); } //set { local_enclosure_path = value; } } [DatabaseColumn] public long MaxItemCount { get { return maxItemCount; } set { maxItemCount = value; } } [DatabaseColumn] public DateTime PubDate { get { return pubDate; } set { pubDate = value; } } [DatabaseColumn] public DateTime LastBuildDate { get { return last_build_date; } set { last_build_date = value; } } /*private DateTime last_downloaded; [DatabaseColumn] public DateTime LastDownloaded { get { return last_downloaded; } set { last_downloaded = value; } }*/ [DatabaseColumn] public FeedSyncSetting SyncSetting { get { return syncSetting; } set { syncSetting = value; } } [DatabaseColumn] protected DateTime last_auto_download = DateTime.MinValue; public DateTime LastAutoDownload { get { return last_auto_download; } set { last_auto_download = value; } } [DatabaseColumn("AutoDownload")] protected FeedAutoDownload auto_download = FeedAutoDownload.None; public FeedAutoDownload AutoDownload { get { return auto_download; } set { if (value == auto_download) return; auto_download = value; CheckForItemsToDownload (); } } [DatabaseColumn("DownloadStatus")] private FeedDownloadStatus download_status; public FeedDownloadStatus DownloadStatus { get { return download_status; } set { download_status = value; } } [DatabaseColumn("IsSubscribed")] private bool is_subscribed; public bool IsSubscribed { get { return is_subscribed; } set { is_subscribed = value; } } #endregion #region Other Properties // TODO remove this, way too redundant with DownloadStatus /*public PodcastFeedActivity Activity { get { return activity; } PodcastFeedActivity ret = PodcastFeedActivity.None; if (this == All) { return ret; } switch (DownloadStatus) { case FeedDownloadStatus.Pending: ret = PodcastFeedActivity.UpdatePending; break; case FeedDownloadStatus.Downloading: ret = PodcastFeedActivity.Updating; break; case FeedDownloadStatus.DownloadFailed: ret = PodcastFeedActivity.UpdateFailed; break; } if (ret != PodcastFeedActivity.Updating) { if (ActiveDownloadCount > 0) { ret = PodcastFeedActivity.ItemsDownloading; } else if (QueuedDownloadCount > 0) { ret = PodcastFeedActivity.ItemsQueued; } } return ret; } }*/ public IEnumerable<FeedItem> Items { get { if (DbId > 0) { foreach (FeedItem item in FeedItem.Provider.FetchAllMatching (String.Format ("{0}.FeedID = {1} ORDER BY {0}.PubDate DESC", FeedItem.Provider.TableName, DbId))) { yield return item; } } } } #endregion private static FeedManager Manager { get { return FeedsManager.Instance.FeedManager; } } #region Constructors public Feed (string url, FeedAutoDownload auto_download) : this () { Url = url; this.auto_download = auto_download; } public Feed () { } #endregion #region Internal Methods // Removing a FeedItem means removing the downloaded file. /*public void Remove (FeedItem item) { if (item == null) { throw new ArgumentNullException ("item"); } if (items.Remove (item)) { inactive_items.Add (item); OnFeedItemRemoved (item); } } }*/ /*public void Remove (IEnumerable<FeedItem> itms) { if (removedItems.Count > 0) { OnItemsChanged (); } } }*/ #endregion #region Private Methods public void SetItems (IEnumerable<FeedItem> items) { bool added_any = false; foreach (FeedItem item in items) { added_any |= AddItem (item); } if (added_any) { CheckForItemsToArchive (); Manager.OnFeedsChanged (); CheckForItemsToDownload (); } } private bool AddItem (FeedItem item) { try { if (!FeedItem.Exists (this.DbId, item.Guid)) { item.Feed = this; item.Save (); return true; } } catch (Exception e) { Hyena.Log.Exception (e); } return false; } /*private void UpdateItems (IEnumerable<FeedItem> new_items) { ICollection<FeedItem> tmpNew = null; List<FeedItem> zombies = new List<FeedItem> (); if (items.Count == 0 && inactive_items.Count == 0) { tmpNew = new List<FeedItem> (new_items); } else { // Get remote items that aren't in the items list tmpNew = Diff (items, new_items); // Of those, remove the ones that are in our inactive list tmpNew = Diff (inactive_items, tmpNew); // Get a list of inactive items that aren't in the remote list any longer ICollection<FeedItem> doubleKilledZombies = Diff ( new_items, inactive_items ); foreach (FeedItem zombie in doubleKilledZombies) { inactive_items.Remove (zombie); } zombies.AddRange (doubleKilledZombies); foreach (FeedItem fi in Diff (new_items, items)) { if (fi.Enclosure != null && !String.IsNullOrEmpty (fi.Enclosure.LocalPath)) { // A hack for the podcast plugin, keeps downloaded items // from being deleted when they are no longer in the feed. continue; } zombies.Add (fi); } } if (tmpNew.Count > 0) { Add (tmpNew); } // TODO merge...should we really be deleting these items? if (zombies.Count > 0) { foreach (FeedItem item in zombies) { if (item.Active) { zombie.Delete (); } } // TODO merge //ItemsTableManager.Delete (zombies); } } // Written before LINQ, will update. private ICollection<FeedItem> Diff (IEnumerable<FeedItem> baseSet, IEnumerable<FeedItem> overlay) { bool found; List<FeedItem> diff = new List<FeedItem> (); foreach (FeedItem opi in overlay) { found = false; foreach (FeedItem bpi in baseSet) { if (opi.Title == bpi.Title && opi.Description == bpi.Description) { found = true; break; } } if (!found) { diff.Add (opi); } } return diff; }*/ #endregion #region Public Methods public void Update () { Manager.QueueUpdate (this); } public void Delete () { Delete (true); Manager.OnFeedsChanged (); } public void Delete (bool deleteEnclosures) { lock (sync) { //if (deleted) // return; //if (updating) { // Manager.CancelUpdate (this); //} foreach (FeedItem item in Items) { item.Delete (deleteEnclosures); } Provider.Delete (this); } //updatingHandle.WaitOne (); Manager.OnFeedsChanged (); } public void MarkAllItemsRead () { lock (sync) { foreach (FeedItem i in Items) { i.IsRead = true; } } } public override string ToString () { return String.Format ("Title: {0} - Url: {1}", Title, Url); } public void Save () { Save (true); } public void Save (bool notify) { Save (notify, true); } public void Save (bool notify, bool download_items) { Provider.Save (this); CheckForItemsToArchive (); if (download_items && (LastBuildDate > LastAutoDownload)) { CheckForItemsToDownload (); } if (notify) { Manager.OnFeedsChanged (); } } private void CheckForItemsToArchive () { if (MaxItemCount == 0) return; int i = 0; foreach (var item in Items) { if (!item.IsRead) { if (i++ >= MaxItemCount) { item.IsRead = true; item.Save (false); } } } } private void CheckForItemsToDownload () { if (LastDownloadError != FeedDownloadError.None || AutoDownload == FeedAutoDownload.None) return; bool only_first = (AutoDownload == FeedAutoDownload.One); bool any = false; foreach (FeedItem item in Items) { if (item.Enclosure != null && item.Active && item.Enclosure.DownloadStatus != FeedDownloadStatus.Downloaded && item.PubDate > LastAutoDownload) { item.Enclosure.AsyncDownload (); any = true; if (only_first) break; } } if (any) { LastAutoDownload = DateTime.Now; // We don't want Save to call CheckForItemsToDownload again Save (true, false); } } /*private bool SetCanceled () { bool ret = false; if (!canceled && updating) { ret = canceled = true; } return ret; }*/ #endregion } }
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 dnsweb.Areas.HelpPage.ModelDescriptions; using dnsweb.Areas.HelpPage.Models; namespace dnsweb.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.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using JetBrains.Annotations; using Masb.NuGet.Multiple.Targeting.Tool.Helpers; using Masb.NuGet.Multiple.Targeting.Tool.InfoModel; using Microsoft.CodeAnalysis; namespace Masb.NuGet.Multiple.Targeting.Tool.RoslynExtensions { public static class RoslynExtensions { private const string ImportPortableCSharp = @"$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets"; private const string ImportPortableVisualBasic = @"$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.VisualBasic.targets"; private const string ImportNuget = @"$(SolutionDir)\.nuget\NuGet.targets"; private const string ImportVisualBasic = @"$(MSBuildToolsPath)\Microsoft.VisualBasic.targets"; private const string ImportCSharp = @"$(MSBuildToolsPath)\Microsoft.CSharp.targets"; private static readonly HashSet<string> frmkNetPortable = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { ImportPortableVisualBasic, ImportPortableCSharp, }; private static readonly HashSet<string> frmkNet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { ImportVisualBasic, ImportCSharp, }; public static async Task<FrameworkName> GetFrameworkName(this Project project) { var xdoc = await XmlHelpers.ReadXDocumentAsync(project.FilePath); XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003"; var version = xdoc.Descendants(msbuild + "TargetFrameworkVersion").Single().Value; var profile = xdoc.Descendants(msbuild + "TargetFrameworkProfile").Single().Value; var imports = xdoc.Descendants(msbuild + "Import").Select(x => x.Attribute("Project").Value).ToArray(); var identifier = imports.Any(x => frmkNetPortable.Contains(x)) ? ".NETPortable" : imports.Any(x => frmkNet.Contains(x)) ? ".NETFramework" : null; version = version.StartsWith("v") ? version.Substring(1) : version; if (identifier != null) return new FrameworkName(identifier, new Version(version), profile); return null; } public static async Task<Project> GetProjectWithReferencesAsync(this Project project) { var frameworkName = await project.GetFrameworkName(); var compilation = await project.GetProjectWithReferencesAsync(frameworkName); return compilation; } public static async Task<Project> GetProjectWithReferencesAsync( [NotNull] this Project project, [NotNull] FrameworkName frameworkName) { if (project == null) throw new ArgumentNullException("project"); if (frameworkName == null) throw new ArgumentNullException("frameworkName"); // some lazy things var lazyTargetFrmkInfo = new Lazy<Task<FrameworkInfo>>( async () => { var frameworkInfo = await FrameworkInfo.GetOrCreateAsync(frameworkName); if (frameworkInfo == null) throw new Exception("Invalid framework name"); return frameworkInfo; }, LazyThreadSafetyMode.None); var lazyTargetLibraries = new Lazy<Task<Dictionary<string, string>>>( async () => { var targetFrameworkInfo = await lazyTargetFrmkInfo.Value; return targetFrameworkInfo.AssemblyInfos .ToDictionary( x => x.RelativePath, targetFrameworkInfo.GetAssemblyPath, StringComparer.InvariantCultureIgnoreCase); }, LazyThreadSafetyMode.None); // The new list of references, that will replace the current project references. var newRefsList = new List<MetadataReference>(project.MetadataReferences.Count); bool anyChanges = false; // first we need to process already existing references: // - if it's a framework reference: // - if source and target framework differs, replace the reference // - if the target framework doesn't contain the reference, remove it // - if it's not a frmk ref, leave it there var replacements = from item in project.MetadataReferences let itemFrmkName = PathHelper.GetFrameworkName(item.Display) select GetReferenceReplacementAsync( frameworkName, item, itemFrmkName, lazyTargetFrmkInfo, lazyTargetLibraries); foreach (var replacement in replacements) { var repl = await replacement; if (repl.NewItem != null) { newRefsList.Add(repl.NewItem); if (!repl.OldItem.Equals(repl.NewItem)) anyChanges = true; } } // second, we need to open the project file and scan for references that may be missing if (project.FilePath != null) { string[] pathsToInclude = null; { var xdoc = XDocument.Load(project.FilePath); XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003"; var references = xdoc.Descendants(msbuild + "ItemGroup").Descendants(msbuild + "Reference"); pathsToInclude = ( from re in references let include = new AssemblyName(re.Attribute("Include").Value) let hintPath = re.Element("HintPath").With(e => e == null ? null : e.Value) select GetAssemblyPath(project, hintPath, include) ) .Where(x => x != null) .Concat(new[] { "~\\mscorlib.dll" }) .Distinct() .ToArray(); } var alreadyAdded = new HashSet<string>( newRefsList.Select(x => x.Display), StringComparer.InvariantCultureIgnoreCase); foreach (var path in pathsToInclude) { if (path == null) continue; if (path.StartsWith("~\\")) { var frameworkInfo = await lazyTargetFrmkInfo.Value; var newAssembly = await frameworkInfo.GetAssemblyInfoByRelativePathAsync(path); var libraries = await lazyTargetLibraries.Value; if (newAssembly != null && libraries.ContainsKey(path)) { var newAssemblyPath = frameworkInfo.GetAssemblyPath(newAssembly); if (!alreadyAdded.Contains(newAssemblyPath)) { var newFrmkRef = MetadataReference.CreateFromFile(newAssemblyPath); newRefsList.Add(newFrmkRef); anyChanges = true; } } } else { var newAssemblyPath = PathHelper.Combine(project.FilePath, path); if (!alreadyAdded.Contains(newAssemblyPath) && File.Exists(newAssemblyPath)) { var newFrmkRef = MetadataReference.CreateFromFile(newAssemblyPath); newRefsList.Add(newFrmkRef); anyChanges = true; } } } } // finally replacing all references, if needed if (anyChanges) project = project.WithMetadataReferences(newRefsList); return project; } private static string GetAssemblyPath(Project project, string hintPath, AssemblyName include) { if (hintPath != null) return PathHelper.Combine(project.FilePath, hintPath); if (include.Version != null && include.GetPublicKeyToken().Length > 0) { try { return Assembly.ReflectionOnlyLoad(include.FullName).Location; } catch { return null; } } return string.Format("~\\{0}.dll", include.Name); } private static async Task<DiffItem<MetadataReference>> GetReferenceReplacementAsync( FrameworkName frameworkName, MetadataReference item, FrameworkName itemFrmkName, Lazy<Task<FrameworkInfo>> lazyTargetFrameworkInfo, Lazy<Task<Dictionary<string, string>>> lazyTargetLibraries) { if (item == null || itemFrmkName.Equals(frameworkName)) return new DiffItem<MetadataReference>(item, item); string relativePath; if (PathHelper.TryGetFrameworkRelativePath(item.Display, out relativePath)) { var frameworkInfo = await lazyTargetFrameworkInfo.Value; var newAssembly = await frameworkInfo.GetAssemblyInfoByRelativePathAsync(relativePath); var libraries = await lazyTargetLibraries.Value; if (newAssembly != null && libraries.ContainsKey(relativePath)) { var newAssemblyPath = frameworkInfo.GetAssemblyPath(newAssembly); var newFrmkRef = MetadataReference.CreateFromFile(newAssemblyPath); return new DiffItem<MetadataReference>(item, newFrmkRef); } } return new DiffItem<MetadataReference>(item, null); } /// <summary> /// Determines whether a metadata reference is a framework reference or not. /// </summary> /// <param name="reference">Metadata reference to test.</param> /// <returns>True if the metadata reference refers to a framework assembly.</returns> public static bool IsFrameworkReference(this MetadataReference reference) { var path = reference.Display; return IsFrameworkReference(path); } private static bool IsFrameworkReference(string path) { var frmkName = PathHelper.GetFrameworkName(path); return frmkName != null; } /// <summary> /// Recompiles a compilation with a new target framework. /// </summary> /// <param name="compilation">Compilation to recompile.</param> /// <param name="frameworkInfo">New target framework.</param> /// <param name="relativeReferences">Framework references that need to be added.</param> /// <returns>A new compilation targeting the passed framework.</returns> public static async Task<Compilation> RecompileWithReferencesAsync( [NotNull] this Compilation compilation, [NotNull] FrameworkInfo frameworkInfo, [NotNull] IEnumerable<string> relativeReferences) { if (compilation == null) throw new ArgumentNullException("compilation"); if (frameworkInfo == null) throw new ArgumentNullException("frameworkInfo"); if (relativeReferences == null) throw new ArgumentNullException("relativeReferences"); var includesRelPaths = new HashSet<string>(relativeReferences, StringComparer.InvariantCultureIgnoreCase); includesRelPaths.RemoveWhere(string.IsNullOrWhiteSpace); // getting current framework references and then // - if present in the new target framework: replace by the new reference // - otherwise: remove the reference var currentFrmkRefs = compilation.References .Where(IsFrameworkReference) .ToArray(); var refsToRemove = new List<MetadataReference>(currentFrmkRefs.Length); foreach (var eachFrmkRef in currentFrmkRefs) { string relativePath; if (PathHelper.TryGetFrameworkRelativePath(eachFrmkRef.Display, out relativePath)) { var newAssembly = await frameworkInfo.GetAssemblyInfoByRelativePathAsync(relativePath); if (newAssembly != null) { var newAssemblyPath = frameworkInfo.GetAssemblyPath(newAssembly); var newFrmkRef = MetadataReference.CreateFromFile(newAssemblyPath); compilation = compilation.ReplaceReference(eachFrmkRef, newFrmkRef); } else { refsToRemove.Add(eachFrmkRef); } // removing already existing references from the include list includesRelPaths.Remove(relativePath); } } compilation = compilation.RemoveReferences(refsToRemove); // creating the new inclusion list var includesTasks = includesRelPaths .OrderBy(x => x) .Select(frameworkInfo.GetAssemblyInfoByRelativePathAsync) .ThenSelect(frameworkInfo.GetAssemblyPath) .ThenSelect(x => MetadataReference.CreateFromFile(x)); var includes = (await Task.WhenAll(includesTasks)) .OfType<MetadataReference>() .ToArray(); compilation = compilation.AddReferences(includes); return compilation; } /// <summary> /// Gets the full name of a type or namespace symbol, including the owning namespace names separated by '.' character. /// </summary> /// <param name="symbol"></param> /// <returns></returns> public static string GetTypeFullName(this INamespaceOrTypeSymbol symbol) { var ns = symbol.ContainingNamespace; return ns == null || !ns.IsGlobalNamespace ? GetTypeFullName((INamespaceOrTypeSymbol)symbol.ContainingSymbol) + "." + GetSymbolName(symbol) : GetSymbolName(symbol); } public static string GetSymbolName(this INamespaceOrTypeSymbol symbol) { var type = symbol as INamedTypeSymbol; if (type != null && type.Arity > 0) return type.Name + "`" + type.Arity; return symbol.Name; } public static string[] GetVariance(this INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeParameters.Any(tp => tp.Variance != VarianceKind.None)) return typeSymbol.TypeParameters .Select(tp => tp.Variance.ToString().ToLowerInvariant()) .ToArray(); return null; } } public struct DiffItem<T> { public readonly T OldItem; public readonly T NewItem; public DiffItem(T oldItem, T newItem) { this.OldItem = oldItem; this.NewItem = newItem; } } internal static class ObjectExtensions { public static TOut With<T, TOut>(this T obj, [NotNull] Func<T, TOut> func) { if (func == null) throw new ArgumentNullException("func"); return func(obj); } } }
using System; using System.Collections.Generic; using System.Globalization; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Provides access to configuration variables for a repository. /// </summary> public class Configuration : IDisposable { private readonly string globalConfigPath; private readonly string systemConfigPath; private readonly Repository repository; private ConfigurationSafeHandle systemHandle; private ConfigurationSafeHandle globalHandle; private ConfigurationSafeHandle localHandle; internal Configuration(Repository repository) { this.repository = repository; globalConfigPath = ConvertPath(NativeMethods.git_config_find_global); systemConfigPath = ConvertPath(NativeMethods.git_config_find_system); Init(); } /// <summary> /// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref = "Repository" /> instead. /// </summary> public Configuration() : this(null) { } /// <summary> /// Determines if there is a local repository level Git configuration file. /// </summary> private bool HasLocalConfig { get { return localHandle != null; } } /// <summary> /// Determines if a Git configuration file specific to the current interactive user has been found. /// </summary> public bool HasGlobalConfig { get { return globalConfigPath != null; } } /// <summary> /// Determines if a system-wide Git configuration file has been found. /// </summary> public bool HasSystemConfig { get { return systemConfigPath != null; } } private static string ConvertPath(Func<byte[], int> pathRetriever) { var buffer = new byte[NativeMethods.GIT_PATH_MAX]; int result = pathRetriever(buffer); //TODO: Make libgit2 return different codes to clearly identify a not found file (GIT_ENOTFOUND ) from any other error (!= GIT_SUCCESS) if (result != (int)GitErrorCode.GIT_SUCCESS) { return null; } return Utf8Marshaler.Utf8FromBuffer(buffer); } internal ConfigurationSafeHandle LocalHandle { get { return localHandle; } } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// Saves any open configuration files. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion /// <summary> /// Delete a configuration variable (key and value). /// </summary> /// <param name = "key">The key to delete.</param> public void Delete(string key) { Ensure.Success(NativeMethods.git_config_delete(localHandle, key)); Save(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> protected virtual void Dispose(bool disposing) { localHandle.SafeDispose(); globalHandle.SafeDispose(); systemHandle.SafeDispose(); } private static T ProcessReadResult<T>(int res, T value, T defaultValue, Func<object, T> postProcessor = null) { if (res == (int)GitErrorCode.GIT_ENOTFOUND) { return defaultValue; } Ensure.Success(res); if (postProcessor == null) { return value; } return postProcessor(value); } private readonly IDictionary<Type, Func<string, object, ConfigurationSafeHandle, object>> configurationTypedRetriever = ConfigurationTypedRetriever(); private static Dictionary<Type, Func<string, object, ConfigurationSafeHandle, object>> ConfigurationTypedRetriever() { var dic = new Dictionary<Type, Func<string, object, ConfigurationSafeHandle, object>>(); dic.Add(typeof(int), (key, dv, handle) => { int value; int res = NativeMethods.git_config_get_int32(handle, key, out value); return ProcessReadResult<object>(res, value, dv); }); dic.Add(typeof(long), (key, dv, handle) => { long value; int res = NativeMethods.git_config_get_int64(handle, key, out value); return ProcessReadResult<object>(res, value, dv); }); dic.Add(typeof(bool), (key, dv, handle) => { bool value; int res = NativeMethods.git_config_get_bool(handle, key, out value); return ProcessReadResult<object>(res, value, dv); }); dic.Add(typeof(string), (key, dv, handle) => { IntPtr value; int res = NativeMethods.git_config_get_string(handle, key, out value); return ProcessReadResult<object>(res, value, dv, s => ((IntPtr)s).MarshallAsString()); }); return dic; } /// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;("core.bare", false); /// </code> /// </para> /// </summary> /// <typeparam name = "T">The configuration value type</typeparam> /// <param name = "key">The key</param> /// <param name = "defaultValue">The default value</param> /// <returns>The configuration value, or <c>defaultValue</c> if not set</returns> public T Get<T>(string key, T defaultValue) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); if (!configurationTypedRetriever.ContainsKey(typeof(T))) { throw new ArgumentException(string.Format("Generic Argument of type '{0}' is not supported.", typeof(T).FullName)); } ConfigurationSafeHandle handle = (LocalHandle ?? globalHandle) ?? systemHandle; if (handle == null) { throw new LibGit2Exception("Could not find a local, global or system level configuration."); } return (T)configurationTypedRetriever[typeof(T)](key, defaultValue, handle); } /// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;("core", "bare", false); /// </code> /// </para> /// </summary> /// <typeparam name = "T">The configuration value type</typeparam> /// <param name = "firstKeyPart">The first key part</param> /// <param name = "secondKeyPart">The second key part</param> /// <param name = "defaultValue">The default value</param> /// <returns>The configuration value, or <c>defaultValue</c> if not set</returns> public T Get<T>(string firstKeyPart, string secondKeyPart, T defaultValue) { Ensure.ArgumentNotNull(firstKeyPart, "firstKeyPart"); Ensure.ArgumentNotNull(secondKeyPart, "secondKeyPart"); return Get(new[] { firstKeyPart, secondKeyPart }, defaultValue); } /// <summary> /// Get a configuration value for the given key parts. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [difftool "kdiff3"] /// path = c:/Program Files/KDiff3/kdiff3.exe /// </code> /// /// You would call: /// /// <code> /// string where = repo.Config.Get&lt;string&gt;("difftool", "kdiff3", "path", null); /// </code> /// </para> /// </summary> /// <typeparam name = "T">The configuration value type</typeparam> /// <param name = "firstKeyPart">The first key part</param> /// <param name = "secondKeyPart">The second key part</param> /// <param name = "thirdKeyPart">The third key part</param> /// <param name = "defaultValue">The default value</param> /// <returns>The configuration value, or <c>defaultValue</c> if not set</returns> public T Get<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, T defaultValue) { Ensure.ArgumentNotNull(firstKeyPart, "firstKeyPart"); Ensure.ArgumentNotNull(secondKeyPart, "secondKeyPart"); Ensure.ArgumentNotNull(thirdKeyPart, "secondKeyPart"); return Get(new[] { firstKeyPart, secondKeyPart, thirdKeyPart }, defaultValue); } /// <summary> /// Get a configuration value for the given key parts. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;(new []{ "core", "bare" }, false); /// </code> /// </para> /// </summary> /// <typeparam name = "T">The configuration value type</typeparam> /// <param name = "keyParts">The key parts</param> /// <param name = "defaultValue">The default value</param> /// <returns>The configuration value, or <c>defaultValue</c> if not set</returns> public T Get<T>(string[] keyParts, T defaultValue) { Ensure.ArgumentNotNull(keyParts, "keyParts"); return Get(string.Join(".", keyParts), defaultValue); } private void Init() { if (repository != null) { Ensure.Success(NativeMethods.git_repository_config(out localHandle, repository.Handle)); } if (globalConfigPath != null) { Ensure.Success(NativeMethods.git_config_open_ondisk(out globalHandle, globalConfigPath)); } if (systemConfigPath != null) { Ensure.Success(NativeMethods.git_config_open_ondisk(out systemHandle, systemConfigPath)); } } private void Save() { Dispose(true); Init(); } private readonly IDictionary<Type, Action<string, object, ConfigurationSafeHandle>> configurationTypedUpdater = ConfigurationTypedUpdater(); private static Dictionary<Type, Action<string, object, ConfigurationSafeHandle>> ConfigurationTypedUpdater() { var dic = new Dictionary<Type, Action<string, object, ConfigurationSafeHandle>>(); dic.Add(typeof(int), (key, val, handle) => Ensure.Success(NativeMethods.git_config_set_int32(handle, key, (int)val))); dic.Add(typeof(long), (key, val, handle) => Ensure.Success(NativeMethods.git_config_set_int64(handle, key, (long)val))); dic.Add(typeof(bool), (key, val, handle) => Ensure.Success(NativeMethods.git_config_set_bool(handle, key, (bool)val))); dic.Add(typeof(string), (key, val, handle) => Ensure.Success(NativeMethods.git_config_set_string(handle, key, (string)val))); return dic; } /// <summary> /// Set a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to set the value for this in a .git\config file: /// /// [test] /// boolsetting = true /// /// You would call: /// /// repo.Config.Set("test.boolsetting", true); /// </para> /// </summary> /// <typeparam name = "T"></typeparam> /// <param name = "key"></param> /// <param name = "value"></param> /// <param name = "level"></param> public void Set<T>(string key, T value, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); if (level == ConfigurationLevel.Local && !HasLocalConfig) { throw new LibGit2Exception("No local configuration file has been found. You must use ConfigurationLevel.Global when accessing configuration outside of repository."); } if (level == ConfigurationLevel.Global && !HasGlobalConfig) { throw new LibGit2Exception("No global configuration file has been found."); } if (level == ConfigurationLevel.System && !HasSystemConfig) { throw new LibGit2Exception("No system configuration file has been found."); } ConfigurationSafeHandle h; switch (level) { case ConfigurationLevel.Local: h = localHandle; break; case ConfigurationLevel.Global: h = globalHandle; break; case ConfigurationLevel.System: h = systemHandle; break; default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Configuration level has an unexpected value ('{0}').", Enum.GetName(typeof(ConfigurationLevel), level)), "level"); } if (!configurationTypedUpdater.ContainsKey(typeof(T))) { throw new ArgumentException(string.Format("Generic Argument of type '{0}' is not supported.", typeof(T).FullName)); } configurationTypedUpdater[typeof(T)](key, value, h); Save(); } } }
// ------------------------------------------------------------------------------ // 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.OneDrive.Sdk { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using Microsoft.Graph; /// <summary> /// The type ItemRequest. /// </summary> public partial class ItemRequest : BaseRequest, IItemRequest { /// <summary> /// Constructs a new ItemRequest. /// </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 ItemRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.SdkVersionHeaderPrefix = "onedrive"; } /// <summary> /// Creates the specified Item using PUT. /// </summary> /// <param name="itemToCreate">The Item to create.</param> /// <returns>The created Item.</returns> public System.Threading.Tasks.Task<Item> CreateAsync(Item itemToCreate) { return this.CreateAsync(itemToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Item using PUT. /// </summary> /// <param name="itemToCreate">The Item to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Item.</returns> public async System.Threading.Tasks.Task<Item> CreateAsync(Item itemToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PUT"; var newEntity = await this.SendAsync<Item>(itemToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Item. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Item. /// </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<Item>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Item. /// </summary> /// <returns>The Item.</returns> public System.Threading.Tasks.Task<Item> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Item. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Item.</returns> public async System.Threading.Tasks.Task<Item> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Item>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Item using PATCH. /// </summary> /// <param name="itemToUpdate">The Item to update.</param> /// <returns>The updated Item.</returns> public System.Threading.Tasks.Task<Item> UpdateAsync(Item itemToUpdate) { return this.UpdateAsync(itemToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Item using PATCH. /// </summary> /// <param name="itemToUpdate">The Item to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Item.</returns> public async System.Threading.Tasks.Task<Item> UpdateAsync(Item itemToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Item>(itemToUpdate, 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 IItemRequest Expand(string value) { 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 IItemRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="itemToInitialize">The <see cref="Item"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Item itemToInitialize) { if (itemToInitialize != null && itemToInitialize.AdditionalData != null) { if (itemToInitialize.Permissions != null && itemToInitialize.Permissions.CurrentPage != null) { itemToInitialize.Permissions.AdditionalData = itemToInitialize.AdditionalData; object nextPageLink; itemToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { itemToInitialize.Permissions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (itemToInitialize.Versions != null && itemToInitialize.Versions.CurrentPage != null) { itemToInitialize.Versions.AdditionalData = itemToInitialize.AdditionalData; object nextPageLink; itemToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { itemToInitialize.Versions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (itemToInitialize.Children != null && itemToInitialize.Children.CurrentPage != null) { itemToInitialize.Children.AdditionalData = itemToInitialize.AdditionalData; object nextPageLink; itemToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { itemToInitialize.Children.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (itemToInitialize.Thumbnails != null && itemToInitialize.Thumbnails.CurrentPage != null) { itemToInitialize.Thumbnails.AdditionalData = itemToInitialize.AdditionalData; object nextPageLink; itemToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { itemToInitialize.Thumbnails.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
---------- Program.cs ---------- using System; namespace CSharpTutA.cs { class Program { static void Main(string[] args) { // Create a Rectangle Rectangle rect1; // Add values to it and run the Area method rect1.length = 200; rect1.width = 50; Console.WriteLine("Area of rect1 : {0}", rect1.Area()); // Use a constructor to create a Rectangle Rectangle rect2 = new Rectangle(100, 40); // If you assign one Rectangle to another // you are setting the values and not // creating a reference rect2 = rect1; rect1.length = 33; Console.WriteLine("rect2.length : {0}", rect2.length); // ----- OBJECT ORIENTED PROGRAMMING ----- // A class models real world objects by // defining their attributes (fields) and // capabilities (methods) // Then unlike with structs you can // inherit from a class and create more // specific subclass types // Add a class Project -> Add Class // Create an Animal object // You could also assign values like // fox.name = "Red" Animal fox = new Animal() { name = "Red", sound = "Raaaw" }; // Call the static method Console.WriteLine("# of Animals {0}", Animal.GetNumAnimals()); // You can also create static utility // classes Project -> Add Class Console.WriteLine("Area of Rectangle : {0}", ShapeMath.GetArea("rectangle", 5, 6)); // ----- NULLABLE TYPES ----- // Data types by default cannot have a // value of null. Often null is needed // when you are working with databases // and you can create a null type by // adding a ? to the definition int? randNum = null; // Check for null if(randNum == null) { Console.WriteLine("randNum is null"); } // Another check for null if (!randNum.HasValue) { Console.WriteLine("randNum is null"); } Console.ReadLine(); } // ----- STRUCTS ----- // A struct is a user defined type that // contain multiple fields and methods struct Rectangle { public double length; public double width; // You can create a constructor method // that will set the values for fields public Rectangle(double l=1, double w=1) { length = l; width = w; } public double Area() { return length * width; } } } } ---------- Animal.cs ---------- using System; namespace CSharpTutA.cs { class Animal { // Attributes (fields) that all Animals have // public means can be directly changed // after an object has been created public string name; public string sound; // A constructor sets default values for // fields when an object is created // This is the default constructor if no // parameters are sent public Animal() { name = "No Name"; sound = "No Sound"; numOfAnimals++; } // You can create additonal constructors // but since we are definig defaults you // don't have to public Animal(string name = "No Name") { // This refers to this objects name // instead of the name passed into // the constructor this.name = name; this.sound = "No Sound"; numOfAnimals++; } public Animal(string name = "No Name", string sound = "No Sound") { this.name = name; this.sound = sound; numOfAnimals++; } // Capabilities (methods) that all Animals have public void MakeSound() { Console.WriteLine("{0} says {1}", name, sound); } // static fields and methods belong to the class // A static field has the same value for all // objects of the Animal type static int numOfAnimals = 0; public static int GetNumAnimals() { return numOfAnimals; } } } ---------- ShapeMath.cs ---------- using System; public static class ShapeMath { // This class can only contain static methods // and constant values public static double GetArea(string shape = "", double length1 = 0, double length2 = 0) { if (String.Equals("Rectangle", shape, StringComparison.OrdinalIgnoreCase)) { return length1 * length2; } else if (String.Equals("Triangle", shape, StringComparison.OrdinalIgnoreCase)) { return length1 * (length2 / 2); } else if (String.Equals("Circle", shape, StringComparison.OrdinalIgnoreCase)) { return 3.14159 * Math.Pow(length1, 2); } else { return -1; } } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System.Collections.Generic; using System; using System.Runtime.InteropServices; using System.Linq; using System.Collections; using Soomla; namespace Soomla.Store { /// <summary> /// This class holds the store's meta data including: /// virtual currencies definitions, /// virtual currency packs definitions, /// virtual goods definitions, /// virtual categories definitions, and /// </summary> public class StoreInfo { protected const string TAG = "SOOMLA/UNITY StoreInfo"; // used for Log error messages static StoreInfo _instance = null; static StoreInfo instance { get { if(_instance == null) { #if UNITY_ANDROID && !UNITY_EDITOR _instance = new StoreInfoAndroid(); #elif UNITY_IOS && !UNITY_EDITOR _instance = new StoreInfoIOS(); #else _instance = new StoreInfo(); #endif } return _instance; } } /// <summary> /// NOTE: This function is manually called when you initialize SoomlaStore. You won't need to call /// it on regular use of SOOMLA Store. /// /// Initializes <code>StoreInfo</code>. /// On first initialization, when the database doesn't have any previous version of the store /// metadata, <code>StoreInfo</code> gets loaded from the given <code>IStoreAssets</code>. /// After the first initialization, <code>StoreInfo</code> will be initialized from the database. /// /// IMPORTANT: If you want to override the metadata on the current <code>StoreInfo</code>, you'll have to bump /// the version of your implementation of <code>IStoreAssets</code> in order to remove the /// metadata when the application loads. Bumping the version is done by returning a higher number /// in {@link com.soomla.store.IStoreAssets#getVersion()}. /// </summary> public static void SetStoreAssets(IStoreAssets storeAssets){ SoomlaUtils.LogDebug(TAG, "Setting store assets in SoomlaInfo"); if (storeAssets == null){ SoomlaUtils.LogError(TAG, "The given store assets can't be null!"); return; } instance._setStoreAssets(storeAssets); // At this point we have StoreInfo JSON saved at the local key-value storage. We can just // continue by initializing from DB. initializeFromDB(); } /// <summary> /// Gets the item with the given <c>itemId</c>. /// </summary> /// <param name="itemId">Item id.</param> /// <exception cref="VirtualItemNotFoundException">Exception is thrown if item is not found.</exception> /// <returns>Item with the given id.</returns> public static VirtualItem GetItemByItemId(string itemId) { SoomlaUtils.LogDebug(TAG, "Trying to fetch an item with itemId: " + itemId); VirtualItem item; if (VirtualItems != null && VirtualItems.TryGetValue(itemId, out item)) { return item; } throw new VirtualItemNotFoundException("itemId", itemId); } /// <summary> /// Gets the purchasable item with the given <c>productId</c>. /// </summary> /// <param name="productId">Product id.</param> /// <exception cref="VirtualItemNotFoundException">Exception is thrown if item is not found.</exception> /// <returns>Purchasable virtual item with the given id.</returns> public static PurchasableVirtualItem GetPurchasableItemWithProductId(string productId) { SoomlaUtils.LogDebug(TAG, "Trying to fetch a purchasable item with productId: " + productId); PurchasableVirtualItem item; if (PurchasableItems != null && PurchasableItems.TryGetValue(productId, out item)) { return item; } throw new VirtualItemNotFoundException("productId", productId); } /// <summary> /// Gets the category that the virtual good with the given <c>goodItemId</c> belongs to. /// </summary> /// <param name="goodItemId">Item id.</param> /// <exception cref="VirtualItemNotFoundException">Exception is thrown if category is not found.</exception> /// <returns>Category that the item with given id belongs to.</returns> public static VirtualCategory GetCategoryForVirtualGood(string goodItemId) { SoomlaUtils.LogDebug(TAG, "Trying to fetch a category for a good with itemId: " + goodItemId); VirtualCategory category; if (GoodsCategories != null && GoodsCategories.TryGetValue(goodItemId, out category)) { return category; } throw new VirtualItemNotFoundException("goodItemId of category", goodItemId); } /// <summary> /// Gets the first upgrade for virtual good with the given <c>goodItemId</c>. /// </summary> /// <param name="goodItemId">Item id.</param> /// <returns>The first upgrade for virtual good with the given id.</returns> public static UpgradeVG GetFirstUpgradeForVirtualGood(string goodItemId) { SoomlaUtils.LogDebug(TAG, "Trying to fetch first upgrade of a good with itemId: " + goodItemId); List<UpgradeVG> upgrades; if (GoodsUpgrades != null && GoodsUpgrades.TryGetValue(goodItemId, out upgrades)) { return upgrades.FirstOrDefault(up => string.IsNullOrEmpty(up.PrevItemId)); } return null; } /// <summary> /// Gets the last upgrade for the virtual good with the given <c>goodItemId</c>. /// </summary> /// <param name="goodItemId">item id</param> /// <returns>last upgrade for virtual good with the given id</returns> public static UpgradeVG GetLastUpgradeForVirtualGood(string goodItemId) { SoomlaUtils.LogDebug(TAG, "Trying to fetch last upgrade of a good with itemId: " + goodItemId); List<UpgradeVG> upgrades; if (GoodsUpgrades != null && GoodsUpgrades.TryGetValue(goodItemId, out upgrades)) { return upgrades.FirstOrDefault(up => string.IsNullOrEmpty(up.NextItemId)); } return null; } /// <summary> /// Gets all the upgrades for the virtual good with the given <c>goodItemId</c>. /// </summary> /// <param name="goodItemId">Item id.</param> /// <returns>All upgrades for virtual good with the given id.</returns> public static List<UpgradeVG> GetUpgradesForVirtualGood(string goodItemId) { SoomlaUtils.LogDebug(TAG, "Trying to fetch upgrades of a good with itemId: " + goodItemId); List<UpgradeVG> upgrades; if (GoodsUpgrades != null && GoodsUpgrades.TryGetValue(goodItemId, out upgrades)) { return upgrades; } return null; } /// <summary> /// Saves the store's metadata in the database as JSON. /// </summary> public static void Save() { string store_json = toJSONObject().print(); SoomlaUtils.LogDebug(TAG, "saving StoreInfo to DB. json is: " + store_json); string key = keyMetaStoreInfo(); KeyValueStorage.SetValue(key, store_json); instance.loadNativeFromDB(); } /// <summary> /// Replaces the given virtual item, and then saves the store's metadata /// (if requested). /// </summary> /// <param name="virtualItem">the virtual item to replace.</param> /// <param name="saveToDB">should the virtual item be persisted to local DB</param> public static void Save(VirtualItem virtualItem, bool saveToDB = true) { replaceVirtualItem(virtualItem); if (saveToDB) { Save(); } } /// <summary> /// Replaces the given virtual item, and then saves the store's metadata /// (if requested). /// </summary> /// <param name="virtualItem">the virtual item to replace.</param> /// <param name="saveToDB">should the virtual item be persisted to local DB</param> public static void Save(List<VirtualItem> virtualItems, bool saveToDB = true) { if ((virtualItems == null) && (virtualItems.Count == 0)) { return; } foreach(VirtualItem virtualItem in virtualItems) { replaceVirtualItem(virtualItem); } if (saveToDB) { Save(); } } /** Protected Functions **/ /** These protected virtual functions will only run when in editor **/ virtual protected void _setStoreAssets(IStoreAssets storeAssets) { #if UNITY_EDITOR string storeJSON = IStoreAssetsToJSON(storeAssets); KeyValueStorage.SetValue(keyMetaStoreInfo(), storeJSON); #endif } protected virtual void loadNativeFromDB() { /* no implementation for this in editor... only devcies */ } /** Protected Functions **/ protected static string IStoreAssetsToJSON(IStoreAssets storeAssets) { // Utils.LogDebug(TAG, "Adding currency"); JSONObject currencies = new JSONObject(JSONObject.Type.ARRAY); foreach(VirtualCurrency vi in storeAssets.GetCurrencies()) { currencies.Add(vi.toJSONObject()); } // Utils.LogDebug(TAG, "Adding packs"); JSONObject packs = new JSONObject(JSONObject.Type.ARRAY); foreach(VirtualCurrencyPack vi in storeAssets.GetCurrencyPacks()) { packs.Add(vi.toJSONObject()); } // Utils.LogDebug(TAG, "Adding goods"); JSONObject suGoods = new JSONObject(JSONObject.Type.ARRAY); JSONObject ltGoods = new JSONObject(JSONObject.Type.ARRAY); JSONObject eqGoods = new JSONObject(JSONObject.Type.ARRAY); JSONObject upGoods = new JSONObject(JSONObject.Type.ARRAY); JSONObject paGoods = new JSONObject(JSONObject.Type.ARRAY); foreach(VirtualGood g in storeAssets.GetGoods()){ if (g is SingleUseVG) { suGoods.Add(g.toJSONObject()); } else if (g is EquippableVG) { eqGoods.Add(g.toJSONObject()); } else if (g is UpgradeVG) { upGoods.Add(g.toJSONObject()); } else if (g is LifetimeVG) { ltGoods.Add(g.toJSONObject()); } else if (g is SingleUsePackVG) { paGoods.Add(g.toJSONObject()); } } JSONObject goods = new JSONObject(JSONObject.Type.OBJECT); goods.AddField(StoreJSONConsts.STORE_GOODS_SU, suGoods); goods.AddField(StoreJSONConsts.STORE_GOODS_LT, ltGoods); goods.AddField(StoreJSONConsts.STORE_GOODS_EQ, eqGoods); goods.AddField(StoreJSONConsts.STORE_GOODS_UP, upGoods); goods.AddField(StoreJSONConsts.STORE_GOODS_PA, paGoods); // Utils.LogDebug(TAG, "Adding categories"); JSONObject categories = new JSONObject(JSONObject.Type.ARRAY); foreach(VirtualCategory vi in storeAssets.GetCategories()) { categories.Add(vi.toJSONObject()); } // Utils.LogDebug(TAG, "Preparing StoreAssets JSONObject"); JSONObject storeAssetsObj = new JSONObject(JSONObject.Type.OBJECT); storeAssetsObj.AddField(StoreJSONConsts.STORE_CATEGORIES, categories); storeAssetsObj.AddField(StoreJSONConsts.STORE_CURRENCIES, currencies); storeAssetsObj.AddField(StoreJSONConsts.STORE_CURRENCYPACKS, packs); storeAssetsObj.AddField(StoreJSONConsts.STORE_GOODS, goods); return storeAssetsObj.print(); } /** Private functions **/ private static void initializeFromDB() { string key = keyMetaStoreInfo(); string val = KeyValueStorage.GetValue(key); if (string.IsNullOrEmpty(val)){ SoomlaUtils.LogError(TAG, "store json is not in DB. Make sure you initialized SoomlaStore with your Store assets. The App will shut down now."); Application.Quit(); } SoomlaUtils.LogDebug(TAG, "the metadata-economy json (from DB) is " + val); JSONObject storeJSON = new JSONObject (val); fromJSONObject (storeJSON); } private static void fromJSONObject(JSONObject storeJSON) { VirtualItems = new Dictionary<string, VirtualItem> (); PurchasableItems = new Dictionary<string, PurchasableVirtualItem> (); GoodsCategories = new Dictionary<string, VirtualCategory> (); GoodsUpgrades = new Dictionary<string, List<UpgradeVG>> (); CurrencyPacks = new List<VirtualCurrencyPack> (); Goods = new List<VirtualGood> (); Categories = new List<VirtualCategory> (); Currencies = new List<VirtualCurrency> (); if (storeJSON.HasField (StoreJSONConsts.STORE_CURRENCIES)) { List<JSONObject> objs = storeJSON [StoreJSONConsts.STORE_CURRENCIES].list; foreach (JSONObject o in objs) { VirtualCurrency c = new VirtualCurrency (o); Currencies.Add (c); } } if (storeJSON.HasField (StoreJSONConsts.STORE_CURRENCYPACKS)) { List<JSONObject> objs = storeJSON [StoreJSONConsts.STORE_CURRENCYPACKS].list; foreach (JSONObject o in objs) { VirtualCurrencyPack c = new VirtualCurrencyPack (o); CurrencyPacks.Add (c); } } if (storeJSON.HasField (StoreJSONConsts.STORE_GOODS)) { JSONObject goods = storeJSON [StoreJSONConsts.STORE_GOODS]; if (goods.HasField (StoreJSONConsts.STORE_GOODS_SU)) { List<JSONObject> suGoods = goods [StoreJSONConsts.STORE_GOODS_SU].list; foreach (JSONObject o in suGoods) { var c = new SingleUseVG (o); Goods.Add (c); } } if (goods.HasField (StoreJSONConsts.STORE_GOODS_LT)) { List<JSONObject> ltGoods = goods [StoreJSONConsts.STORE_GOODS_LT].list; foreach (JSONObject o in ltGoods) { LifetimeVG c = new LifetimeVG (o); Goods.Add (c); } } if (goods.HasField (StoreJSONConsts.STORE_GOODS_EQ)) { List<JSONObject> eqGoods = goods [StoreJSONConsts.STORE_GOODS_EQ].list; foreach (JSONObject o in eqGoods) { EquippableVG c = new EquippableVG (o); Goods.Add (c); } } if (goods.HasField (StoreJSONConsts.STORE_GOODS_PA)) { List<JSONObject> paGoods = goods [StoreJSONConsts.STORE_GOODS_PA].list; foreach (JSONObject o in paGoods) { SingleUsePackVG c = new SingleUsePackVG (o); Goods.Add (c); } } if (goods.HasField (StoreJSONConsts.STORE_GOODS_UP)) { List<JSONObject> upGoods = goods [StoreJSONConsts.STORE_GOODS_UP].list; foreach (JSONObject o in upGoods) { UpgradeVG c = new UpgradeVG (o); Goods.Add (c); } } } if (storeJSON.HasField(StoreJSONConsts.STORE_CATEGORIES)) { List<JSONObject> categories = storeJSON[StoreJSONConsts.STORE_CATEGORIES].list; foreach (JSONObject o in categories){ VirtualCategory category = new VirtualCategory(o); Categories.Add(category); } } updateAggregatedLists (); } private static void updateAggregatedLists (){ // rewritten from android java code foreach (VirtualCurrency vi in Currencies) { VirtualItems.AddOrUpdate(vi.ItemId, vi); } foreach (VirtualCurrencyPack vi in CurrencyPacks) { VirtualItems.AddOrUpdate(vi.ItemId, vi); PurchaseType purchaseType = vi.PurchaseType; if (purchaseType is PurchaseWithMarket) { PurchasableItems.AddOrUpdate(((PurchaseWithMarket)purchaseType).MarketItem.ProductId, vi); } } foreach (VirtualGood vi in Goods) { VirtualItems.AddOrUpdate(vi.ItemId, vi); if (vi is UpgradeVG) { List<UpgradeVG> upgrades; if (!GoodsUpgrades.TryGetValue (((UpgradeVG)vi).GoodItemId, out upgrades)) { upgrades = new List<UpgradeVG> (); GoodsUpgrades.Add(((UpgradeVG)vi).GoodItemId, upgrades); } upgrades.Add ((UpgradeVG)vi); } PurchaseType purchaseType = vi.PurchaseType; if (purchaseType is PurchaseWithMarket) { PurchasableItems.AddOrUpdate(((PurchaseWithMarket)purchaseType).MarketItem.ProductId, vi); } } foreach (VirtualCategory category in Categories) { foreach (string goodItemId in category.GoodItemIds) { GoodsCategories.AddOrUpdate(goodItemId, category); } } } /// <summary> /// Replaces an old virtual item with a new one by doing the following: /// 1. Determines the type of the given virtual item. /// 2. Looks for the given virtual item in the relevant list, according to its type. /// 3. If found, removes it. /// 4. Adds the given virtual item. /// </summary> /// <param name="virtualItem">the virtual item that replaces the old one if exists.</param> private static void replaceVirtualItem(VirtualItem virtualItem) { VirtualItems.AddOrUpdate(virtualItem.ItemId, virtualItem); if (virtualItem is VirtualCurrency) { for(int i=0; i<Currencies.Count(); i++) { if (Currencies[i].ItemId == virtualItem.ItemId) { Currencies.RemoveAt(i); break; } } Currencies.Add((VirtualCurrency)virtualItem); } if (virtualItem is VirtualCurrencyPack) { VirtualCurrencyPack vcp = (VirtualCurrencyPack)virtualItem; if (vcp.PurchaseType is PurchaseWithMarket) { PurchasableItems.AddOrUpdate(((PurchaseWithMarket) vcp.PurchaseType).MarketItem .ProductId, vcp); } for(int i=0; i<CurrencyPacks.Count(); i++) { if (CurrencyPacks[i].ItemId == vcp.ItemId) { CurrencyPacks.RemoveAt(i); break; } } CurrencyPacks.Add(vcp); } if (virtualItem is VirtualGood) { VirtualGood vg = (VirtualGood)virtualItem; if (vg is UpgradeVG) { List<UpgradeVG> upgrades; if (!GoodsUpgrades.TryGetValue (((UpgradeVG) vg).GoodItemId, out upgrades)) { upgrades = new List<UpgradeVG>(); GoodsUpgrades.Add(((UpgradeVG) vg).ItemId, upgrades); } upgrades.Add((UpgradeVG) vg); } if (vg.PurchaseType is PurchaseWithMarket) { PurchasableItems.AddOrUpdate(((PurchaseWithMarket) vg.PurchaseType).MarketItem .ProductId, vg); } for(int i=0; i<Goods.Count(); i++) { if (Goods[i].ItemId == vg.ItemId) { Goods.RemoveAt(i); break; } } Goods.Add(vg); } } /// <summary> /// Converts <code>StoreInfo</code> to a <code>JSONObject</code>. /// </summary> /// <returns><code>JSONObject</code> representation of <code>StoreInfo</code>.</returns> private static JSONObject toJSONObject(){ JSONObject currencies = new JSONObject(JSONObject.Type.ARRAY); foreach(VirtualCurrency c in Currencies){ currencies.Add(c.toJSONObject()); } JSONObject currencyPacks = new JSONObject(JSONObject.Type.ARRAY); foreach (VirtualCurrencyPack pack in CurrencyPacks){ currencyPacks.Add(pack.toJSONObject()); } JSONObject goods = new JSONObject(); JSONObject suGoods = new JSONObject(JSONObject.Type.ARRAY); JSONObject ltGoods = new JSONObject(JSONObject.Type.ARRAY); JSONObject eqGoods = new JSONObject(JSONObject.Type.ARRAY); JSONObject paGoods = new JSONObject(JSONObject.Type.ARRAY); JSONObject upGoods = new JSONObject(JSONObject.Type.ARRAY); foreach (VirtualGood good in Goods){ if (good is SingleUseVG) { suGoods.Add(good.toJSONObject()); } else if (good is UpgradeVG) { upGoods.Add(good.toJSONObject()); } else if (good is EquippableVG) { eqGoods.Add(good.toJSONObject()); } else if (good is SingleUsePackVG) { paGoods.Add(good.toJSONObject()); } else if (good is LifetimeVG) { ltGoods.Add(good.toJSONObject()); } } JSONObject categories = new JSONObject(JSONObject.Type.ARRAY); foreach (VirtualCategory cat in Categories){ categories.Add(cat.toJSONObject()); } JSONObject jsonObject = new JSONObject(); goods.AddField(StoreJSONConsts.STORE_GOODS_SU, suGoods); goods.AddField(StoreJSONConsts.STORE_GOODS_LT, ltGoods); goods.AddField(StoreJSONConsts.STORE_GOODS_EQ, eqGoods); goods.AddField(StoreJSONConsts.STORE_GOODS_PA, paGoods); goods.AddField(StoreJSONConsts.STORE_GOODS_UP, upGoods); jsonObject.AddField(StoreJSONConsts.STORE_CATEGORIES, categories); jsonObject.AddField(StoreJSONConsts.STORE_CURRENCIES, currencies); jsonObject.AddField(StoreJSONConsts.STORE_GOODS, goods); jsonObject.AddField(StoreJSONConsts.STORE_CURRENCYPACKS, currencyPacks); return jsonObject; } /** Lists containing Store metadata **/ // convenient hash of virtual items public static Dictionary<string, VirtualItem> VirtualItems = new Dictionary<string, VirtualItem>(); // convenient hash of purchasable virtual items public static Dictionary<string, PurchasableVirtualItem> PurchasableItems = new Dictionary<string, PurchasableVirtualItem>(); // convenient hash of goods-categories public static Dictionary<string, VirtualCategory> GoodsCategories = new Dictionary<string, VirtualCategory>(); // convenient hash of good-upgrades public static Dictionary<string, List<UpgradeVG>> GoodsUpgrades = new Dictionary<string, List<UpgradeVG>>(); // list of virtual currencies public static List<VirtualCurrency> Currencies = new List<VirtualCurrency>(); // list of currency-packs public static List<VirtualCurrencyPack> CurrencyPacks = new List<VirtualCurrencyPack>(); // list of virtual goods public static List<VirtualGood> Goods = new List<VirtualGood>(); // list of virtul categories public static List<VirtualCategory> Categories = new List<VirtualCategory>(); /** Private Members **/ private static string keyMetaStoreInfo() { return "meta.storeinfo"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Runtime; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions.State { internal class ReadWriteLock<TState> where TState : class, new() { private readonly TransactionalStateOptions options; private readonly TransactionQueue<TState> queue; private BatchWorker lockWorker; private BatchWorker storageWorker; private readonly ILogger logger; private readonly IActivationLifetime activationLifetime; // the linked list of lock groups // the head is the group that is currently holding the lock private LockGroup currentGroup = null; // cache the last known minimum so we don't have to recompute it as much private DateTime cachedMin = DateTime.MaxValue; private Guid cachedMinId; // group of non-conflicting transactions collectively acquiring/releasing the lock private class LockGroup : Dictionary<Guid, TransactionRecord<TState>> { public int FillCount; public List<Action> Tasks; // the tasks for executing the waiting operations public LockGroup Next; // queued-up transactions waiting to acquire lock public DateTime? Deadline; public void Reset() { FillCount = 0; Tasks = null; Deadline = null; Clear(); } } public ReadWriteLock( IOptions<TransactionalStateOptions> options, TransactionQueue<TState> queue, BatchWorker storageWorker, ILogger logger, IActivationLifetime activationLifetime) { this.options = options.Value; this.queue = queue; this.storageWorker = storageWorker; this.logger = logger; this.activationLifetime = activationLifetime; this.lockWorker = new BatchWorkerFromDelegate(LockWork, this.activationLifetime.OnDeactivating); } public async Task<TResult> EnterLock<TResult>(Guid transactionId, DateTime priority, AccessCounter counter, bool isRead, Func<TResult> task) { bool rollbacksOccurred = false; List<Task> cleanup = new List<Task>(); await this.queue.Ready(); // search active transactions if (Find(transactionId, isRead, out var group, out var record)) { // check if we lost some reads or writes already if (counter.Reads > record.NumberReads || counter.Writes > record.NumberWrites) { throw new OrleansBrokenTransactionLockException(transactionId.ToString(), "when re-entering lock"); } // check if the operation conflicts with other transactions in the group if (HasConflict(isRead, priority, transactionId, group, out var resolvable)) { if (!resolvable) { throw new OrleansTransactionLockUpgradeException(transactionId.ToString()); } else { // rollback all conflicts var conflicts = Conflicts(transactionId, group).ToList(); if (conflicts.Count > 0) { foreach (var r in conflicts) { cleanup.Add(Rollback(r, true)); rollbacksOccurred = true; } } } } } else { // check if we were supposed to already hold this lock if (counter.Reads + counter.Writes > 0) { throw new OrleansBrokenTransactionLockException(transactionId.ToString(), "when trying to re-enter lock"); } // update the lock deadline if (group == currentGroup) { group.Deadline = DateTime.UtcNow + this.options.LockTimeout; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("set lock expiration at {Deadline}", group.Deadline.Value.ToString("o")); } // create a new record for this transaction record = new TransactionRecord<TState>() { TransactionId = transactionId, Priority = priority, Deadline = DateTime.UtcNow + this.options.LockAcquireTimeout }; group.Add(transactionId, record); group.FillCount++; if (logger.IsEnabled(LogLevel.Trace)) { if (group == currentGroup) logger.Trace($"enter-lock {transactionId} fc={group.FillCount}"); else logger.Trace($"enter-lock-queue {transactionId} fc={group.FillCount}"); } } var result = new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously); Action completion = () => { try { result.TrySetResult(task()); } catch (Exception exception) { result.TrySetException(exception); } }; if (group != currentGroup) { // task will be executed once its group acquires the lock if (group.Tasks == null) group.Tasks = new List<Action>(); group.Tasks.Add(completion); } else { // execute task right now completion(); } if (isRead) { record.AddRead(); } else { record.AddWrite(); } if (rollbacksOccurred) { lockWorker.Notify(); } else if (group.Deadline.HasValue) { lockWorker.Notify(group.Deadline.Value); } await Task.WhenAll(cleanup); return await result.Task; } public async Task<(TransactionalStatus Status, TransactionRecord<TState> State)> ValidateLock(Guid transactionId, AccessCounter accessCount) { if (currentGroup == null || !currentGroup.TryGetValue(transactionId, out TransactionRecord<TState> record)) { return (TransactionalStatus.BrokenLock, new TransactionRecord<TState>()); } else if (record.NumberReads != accessCount.Reads || record.NumberWrites != accessCount.Writes) { await Rollback(transactionId, true); return (TransactionalStatus.LockValidationFailed, record); } else { return (TransactionalStatus.Ok, record); } } public void Notify() { this.lockWorker.Notify(); } public bool TryGetRecord(Guid transactionId, out TransactionRecord<TState> record) { return this.currentGroup.TryGetValue(transactionId, out record); } public Task AbortExecutingTransactions(Exception exception) { if (currentGroup != null) { Task[] pending = currentGroup.Select(g => BreakLock(g.Key, g.Value, exception)).ToArray(); currentGroup.Reset(); return Task.WhenAll(pending); } return Task.CompletedTask; } private Task BreakLock(Guid transactionId, TransactionRecord<TState> entry, Exception exception) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Break-lock for transaction {TransactionId}", transactionId); return this.queue.NotifyOfAbort(entry, TransactionalStatus.BrokenLock, exception); } public void AbortQueuedTransactions() { var pos = currentGroup?.Next; while (pos != null) { if (pos.Tasks != null) { foreach (var t in pos.Tasks) { // running the task will abort the transaction because it is not in currentGroup t(); } } pos.Clear(); pos = pos.Next; } if (currentGroup != null) currentGroup.Next = null; } public async Task Rollback(Guid guid, bool notify) { // no-op if the transaction never happened or already rolled back if (currentGroup == null || !currentGroup.TryGetValue(guid, out var record)) { return; } // remove record for this transaction currentGroup.Remove(guid); // notify remote listeners if (notify) { await this.queue.NotifyOfAbort(record, TransactionalStatus.BrokenLock, exception: null); } } private async Task LockWork() { // Stop pumping lock work if this activation is stopping/stopped. if (this.activationLifetime.OnDeactivating.IsCancellationRequested) return; using (this.activationLifetime.BlockDeactivation()) { var now = DateTime.UtcNow; if (currentGroup != null) { // check if there are any group members that are ready to exit the lock if (currentGroup.Count > 0) { if (LockExits(out var single, out var multiple)) { if (single != null) { await this.queue.EnqueueCommit(single); } else if (multiple != null) { foreach (var r in multiple) { await this.queue.EnqueueCommit(r); } } lockWorker.Notify(); storageWorker.Notify(); } else if (currentGroup.Deadline.HasValue) { if (currentGroup.Deadline.Value < now) { // the lock group has timed out. string txlist = string.Join(",", currentGroup.Keys.Select(g => g.ToString())); TimeSpan late = now - currentGroup.Deadline.Value; logger.LogWarning("Break-lock timeout for transactions {TransactionIds}. {Late}ms late", txlist, Math.Floor(late.TotalMilliseconds)); await AbortExecutingTransactions(exception: null); lockWorker.Notify(); } else { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("recheck lock expiration at {Deadline}", currentGroup.Deadline.Value.ToString("o")); // check again when the group expires lockWorker.Notify(currentGroup.Deadline.Value); } } else { string txlist = string.Join(",", currentGroup.Keys.Select(g => g.ToString())); logger.LogWarning("Deadline not set for transactions {TransactionIds}", txlist); } } else { // the lock is empty, a new group can enter currentGroup = currentGroup.Next; if (currentGroup != null) { currentGroup.Deadline = now + this.options.LockTimeout; // discard expired waiters that have no chance to succeed // because they have been waiting for the lock for a longer timespan than the // total transaction timeout List<Guid> expiredWaiters = null; foreach (var kvp in currentGroup) { if (now > kvp.Value.Deadline) { if (expiredWaiters == null) expiredWaiters = new List<Guid>(); expiredWaiters.Add(kvp.Key); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace($"expire-lock-waiter {kvp.Key}"); } } if (expiredWaiters != null) { foreach (var guid in expiredWaiters) { currentGroup.Remove(guid); } } if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace($"lock groupsize={currentGroup.Count} deadline={currentGroup.Deadline:o}"); foreach (var kvp in currentGroup) logger.Trace($"enter-lock {kvp.Key}"); } // execute all the read and update tasks if (currentGroup.Tasks != null) { foreach (var t in currentGroup.Tasks) { t(); } } lockWorker.Notify(); } } } } } private bool Find(Guid guid, bool isRead, out LockGroup group, out TransactionRecord<TState> record) { if (currentGroup == null) { group = currentGroup = new LockGroup(); record = null; return false; } else { group = null; var pos = currentGroup; while (true) { if (pos.TryGetValue(guid, out record)) { group = pos; return true; } // if we have not found a place to insert this op yet, and there is room, and no conflicts, use this one if (group == null && pos.FillCount < this.options.MaxLockGroupSize && !HasConflict(isRead, DateTime.MaxValue, guid, pos, out _)) { group = pos; } if (pos.Next == null) // we did not find this tx. { // add a new empty group to insert this tx, if we have not found one yet if (group == null) { group = pos.Next = new LockGroup(); } return false; } pos = pos.Next; } } } private bool HasConflict(bool isRead, DateTime priority, Guid transactionId, LockGroup group, out bool resolvable) { bool foundResolvableConflicts = false; foreach (var kvp in group) { if (kvp.Key != transactionId) { if (isRead && kvp.Value.NumberWrites == 0) { continue; } else { if (priority > kvp.Value.Priority) { resolvable = false; return true; } else { foundResolvableConflicts = true; } } } } resolvable = foundResolvableConflicts; return foundResolvableConflicts; } private IEnumerable<Guid> Conflicts(Guid transactionId, LockGroup group) { foreach (var kvp in group) { if (kvp.Key != transactionId) { yield return kvp.Key; } } } private bool LockExits(out TransactionRecord<TState> single, out List<TransactionRecord<TState>> multiple) { single = null; multiple = null; // fast-path the one-element case if (currentGroup.Count == 1) { var kvp = currentGroup.First(); if (kvp.Value.Role == CommitRole.NotYetDetermined) // has not received commit from TA { return false; } else { single = kvp.Value; currentGroup.Remove(single.TransactionId); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"exit-lock {single.TransactionId} {single.Timestamp:o}"); return true; } } else { // find the current minimum, if we don't have a valid cache of it if (cachedMin == DateTime.MaxValue || !currentGroup.TryGetValue(cachedMinId, out var record) || record.Role != CommitRole.NotYetDetermined || record.Timestamp != cachedMin) { cachedMin = DateTime.MaxValue; foreach (var kvp in currentGroup) { if (kvp.Value.Role == CommitRole.NotYetDetermined) // has not received commit from TA { if (cachedMin > kvp.Value.Timestamp) { cachedMin = kvp.Value.Timestamp; cachedMinId = kvp.Key; } } } } // find released entries foreach (var kvp in currentGroup) { if (kvp.Value.Role != CommitRole.NotYetDetermined) // ready to commit { if (kvp.Value.Timestamp < cachedMin) { if (multiple == null) { multiple = new List<TransactionRecord<TState>>(); } multiple.Add(kvp.Value); } } } if (multiple == null) { return false; } else { multiple.Sort(Comparer); for (int i = 0; i < multiple.Count; i++) { currentGroup.Remove(multiple[i].TransactionId); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"exit-lock ({i}/{multiple.Count}) {multiple[i].TransactionId} {multiple[i].Timestamp:o}"); } return true; } } } private static int Comparer(TransactionRecord<TState> a, TransactionRecord<TState> b) { return a.Timestamp.CompareTo(b.Timestamp); } } }
//------------------------------------------------------------------------------ // <copyright file="SqlDataReader.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.SqlClient { using System.Threading; using System.Diagnostics; using System.Reflection; using System; using System.Data; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Data.Sql; using System.Data.SqlTypes; using System.Data.Common; using System.Data.ProviderBase; using System.ComponentModel; using System.Globalization; using System.Xml; using System.Runtime.InteropServices; internal sealed class SqlBuffer { internal enum StorageType { Empty = 0, Boolean, Byte, DateTime, Decimal, Double, Int16, Int32, Int64, Money, Single, String, SqlBinary, SqlCachedBuffer, SqlGuid, SqlXml, Date, DateTime2, DateTimeOffset, Time, } internal struct DateTimeInfo { // This is used to store DateTime internal Int32 daypart; internal Int32 timepart; } internal struct NumericInfo { // This is used to store Decimal data internal Int32 data1; internal Int32 data2; internal Int32 data3; internal Int32 data4; internal Byte precision; internal Byte scale; internal Boolean positive; } internal struct TimeInfo { internal Int64 ticks; internal byte scale; } internal struct DateTime2Info { internal Int32 date; internal TimeInfo timeInfo; } internal struct DateTimeOffsetInfo { internal DateTime2Info dateTime2Info; internal Int16 offset; } [StructLayout(LayoutKind.Explicit)] internal struct Storage { [FieldOffset(0)] internal Boolean _boolean; [FieldOffset(0)] internal Byte _byte; [FieldOffset(0)] internal DateTimeInfo _dateTimeInfo; [FieldOffset(0)] internal Double _double; [FieldOffset(0)] internal NumericInfo _numericInfo; [FieldOffset(0)] internal Int16 _int16; [FieldOffset(0)] internal Int32 _int32; [FieldOffset(0)] internal Int64 _int64; // also used to store Money, UtcDateTime, Date , and Time [FieldOffset(0)] internal Single _single; [FieldOffset(0)] internal TimeInfo _timeInfo; [FieldOffset(0)] internal DateTime2Info _dateTime2Info; [FieldOffset(0)] internal DateTimeOffsetInfo _dateTimeOffsetInfo; } private bool _isNull; private StorageType _type; private Storage _value; private object _object; // String, SqlBinary, SqlCachedBuffer, SqlGuid, SqlString, SqlXml internal SqlBuffer() { } private SqlBuffer(SqlBuffer value) { // Clone // value types _isNull = value._isNull; _type = value._type; // ref types - should also be read only unless at some point we allow this data // to be mutable, then we will need to copy _value = value._value; _object = value._object; } internal bool IsEmpty { get { return (StorageType.Empty == _type); } } internal bool IsNull { get { return _isNull; } } internal StorageType VariantInternalStorageType { get { return _type; } } internal Boolean Boolean { get { ThrowIfNull(); if (StorageType.Boolean == _type) { return _value._boolean; } return (Boolean)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _value._boolean = value; _type = StorageType.Boolean; _isNull = false; } } internal Byte Byte { get { ThrowIfNull(); if (StorageType.Byte == _type) { return _value._byte; } return (Byte)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _value._byte = value; _type = StorageType.Byte; _isNull = false; } } internal Byte[] ByteArray { get { ThrowIfNull(); return this.SqlBinary.Value; // } } internal DateTime DateTime { get { ThrowIfNull(); if (StorageType.Date == _type) { return DateTime.MinValue.AddDays(_value._int32); } if (StorageType.DateTime2 == _type) { return new DateTime(GetTicksFromDateTime2Info(_value._dateTime2Info)); } if (StorageType.DateTime == _type) { return SqlDateTime.ToDateTime(_value._dateTimeInfo.daypart, _value._dateTimeInfo.timepart); } return (DateTime)this.Value; // anything else we haven't thought of goes through boxing. } } internal Decimal Decimal { get { ThrowIfNull(); if (StorageType.Decimal == _type) { if (_value._numericInfo.data4 != 0 || _value._numericInfo.scale > 28) { throw new OverflowException(SQLResource.ConversionOverflowMessage); } return new Decimal(_value._numericInfo.data1, _value._numericInfo.data2, _value._numericInfo.data3, !_value._numericInfo.positive, _value._numericInfo.scale); } if (StorageType.Money == _type) { long l = _value._int64; bool isNegative = false; if (l < 0) { isNegative = true; l = -l; } return new Decimal((int)(l & 0xffffffff), (int)(l >> 32), 0, isNegative, 4); } return (Decimal)this.Value; // anything else we haven't thought of goes through boxing. } } internal Double Double { get { ThrowIfNull(); if (StorageType.Double == _type) { return _value._double; } return (Double)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _value._double = value; _type = StorageType.Double; _isNull = false; } } internal Guid Guid { get { // ThrowIfNull(); return this.SqlGuid.Value; } } internal Int16 Int16 { get { ThrowIfNull(); if (StorageType.Int16 == _type) { return _value._int16; } return (Int16)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _value._int16 = value; _type = StorageType.Int16; _isNull = false; } } internal Int32 Int32 { get { ThrowIfNull(); if (StorageType.Int32 == _type) { return _value._int32; } return (Int32)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _value._int32 = value; _type = StorageType.Int32; _isNull = false; } } internal Int64 Int64 { get { ThrowIfNull(); if (StorageType.Int64 == _type) { return _value._int64; } return (Int64)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _value._int64 = value; _type = StorageType.Int64; _isNull = false; } } internal Single Single { get { ThrowIfNull(); if (StorageType.Single == _type) { return _value._single; } return (Single)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _value._single = value; _type = StorageType.Single; _isNull = false; } } internal String String { get { ThrowIfNull(); if (StorageType.String == _type) { return (String)_object; } else if (StorageType.SqlCachedBuffer == _type) { return ((SqlCachedBuffer)(_object)).ToString(); } return (String)this.Value; // anything else we haven't thought of goes through boxing. } } // use static list of format strings indexed by scale for perf! private static string[] __katmaiDateTimeOffsetFormatByScale = new string[] { "yyyy-MM-dd HH:mm:ss zzz", "yyyy-MM-dd HH:mm:ss.f zzz", "yyyy-MM-dd HH:mm:ss.ff zzz", "yyyy-MM-dd HH:mm:ss.fff zzz", "yyyy-MM-dd HH:mm:ss.ffff zzz", "yyyy-MM-dd HH:mm:ss.fffff zzz", "yyyy-MM-dd HH:mm:ss.ffffff zzz", "yyyy-MM-dd HH:mm:ss.fffffff zzz", }; private static string[] __katmaiDateTime2FormatByScale = new string[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.f", "yyyy-MM-dd HH:mm:ss.ff", "yyyy-MM-dd HH:mm:ss.fff", "yyyy-MM-dd HH:mm:ss.ffff", "yyyy-MM-dd HH:mm:ss.fffff", "yyyy-MM-dd HH:mm:ss.ffffff", "yyyy-MM-dd HH:mm:ss.fffffff", }; private static string[] __katmaiTimeFormatByScale = new string[] { "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff", "HH:mm:ss.ffff", "HH:mm:ss.fffff", "HH:mm:ss.ffffff", "HH:mm:ss.fffffff", }; internal string KatmaiDateTimeString { get { ThrowIfNull(); if (StorageType.Date == _type) { return this.DateTime.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo); } if (StorageType.Time == _type) { byte scale = _value._timeInfo.scale; return new DateTime(_value._timeInfo.ticks).ToString(__katmaiTimeFormatByScale[scale], DateTimeFormatInfo.InvariantInfo); } if (StorageType.DateTime2 == _type) { byte scale = _value._dateTime2Info.timeInfo.scale; return this.DateTime.ToString(__katmaiDateTime2FormatByScale[scale], DateTimeFormatInfo.InvariantInfo); } if (StorageType.DateTimeOffset == _type) { DateTimeOffset dto = this.DateTimeOffset; byte scale = _value._dateTimeOffsetInfo.dateTime2Info.timeInfo.scale; return dto.ToString(__katmaiDateTimeOffsetFormatByScale[scale], DateTimeFormatInfo.InvariantInfo); } return (String)this.Value; // anything else we haven't thought of goes through boxing. } } internal SqlString KatmaiDateTimeSqlString { get { if (StorageType.Date == _type || StorageType.Time == _type || StorageType.DateTime2 == _type || StorageType.DateTimeOffset == _type) { if (IsNull) { return SqlString.Null; } return new SqlString(KatmaiDateTimeString); } return (SqlString)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal TimeSpan Time { get { ThrowIfNull(); if (StorageType.Time == _type) { return new TimeSpan(_value._timeInfo.ticks); } return (TimeSpan)this.Value; // anything else we haven't thought of goes through boxing. } } internal DateTimeOffset DateTimeOffset { get { ThrowIfNull(); if (StorageType.DateTimeOffset == _type) { TimeSpan offset = new TimeSpan(0, _value._dateTimeOffsetInfo.offset, 0); // datetime part presents time in UTC return new DateTimeOffset(GetTicksFromDateTime2Info(_value._dateTimeOffsetInfo.dateTime2Info) + offset.Ticks, offset); } return (DateTimeOffset)this.Value; // anything else we haven't thought of goes through boxing. } } private static long GetTicksFromDateTime2Info(DateTime2Info dateTime2Info) { return (dateTime2Info.date * TimeSpan.TicksPerDay + dateTime2Info.timeInfo.ticks); } internal SqlBinary SqlBinary { get { if (StorageType.SqlBinary == _type) { return (SqlBinary)_object; } return (SqlBinary)this.SqlValue; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.SqlBinary; _isNull = value.IsNull; } } internal SqlBoolean SqlBoolean { get { if (StorageType.Boolean == _type) { if (IsNull) { return SqlBoolean.Null; } return new SqlBoolean(_value._boolean); } return (SqlBoolean)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlByte SqlByte { get { if (StorageType.Byte == _type) { if (IsNull) { return SqlByte.Null; } return new SqlByte(_value._byte); } return (SqlByte)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlCachedBuffer SqlCachedBuffer { get { if (StorageType.SqlCachedBuffer == _type) { if (IsNull) { return SqlCachedBuffer.Null; } return (SqlCachedBuffer)_object; } return (SqlCachedBuffer)this.SqlValue; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.SqlCachedBuffer; _isNull = value.IsNull; } } internal SqlXml SqlXml { get { if (StorageType.SqlXml == _type) { if (IsNull) { return SqlXml.Null; } return (SqlXml)_object; } return (SqlXml)this.SqlValue; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.SqlXml; _isNull = value.IsNull; } } internal SqlDateTime SqlDateTime { get { if (StorageType.DateTime == _type) { if (IsNull) { return SqlDateTime.Null; } return new SqlDateTime(_value._dateTimeInfo.daypart, _value._dateTimeInfo.timepart); } return (SqlDateTime)SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlDecimal SqlDecimal { get { if (StorageType.Decimal == _type) { if (IsNull) { return SqlDecimal.Null; } return new SqlDecimal(_value._numericInfo.precision, _value._numericInfo.scale, _value._numericInfo.positive, _value._numericInfo.data1, _value._numericInfo.data2, _value._numericInfo.data3, _value._numericInfo.data4 ); } return (SqlDecimal)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlDouble SqlDouble { get { if (StorageType.Double == _type) { if (IsNull) { return SqlDouble.Null; } return new SqlDouble(_value._double); } return (SqlDouble)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlGuid SqlGuid { get { if (StorageType.SqlGuid == _type) { return (SqlGuid)_object; } return (SqlGuid)this.SqlValue; // anything else we haven't thought of goes through boxing. } set { Debug.Assert (IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.SqlGuid; _isNull = value.IsNull; } } internal SqlInt16 SqlInt16 { get { if (StorageType.Int16 == _type) { if (IsNull) { return SqlInt16.Null; } return new SqlInt16(_value._int16); } return (SqlInt16)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlInt32 SqlInt32 { get { if (StorageType.Int32 == _type) { if (IsNull) { return SqlInt32.Null; } return new SqlInt32(_value._int32); } return (SqlInt32)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlInt64 SqlInt64 { get { if (StorageType.Int64 == _type) { if (IsNull) { return SqlInt64.Null; } return new SqlInt64(_value._int64); } return (SqlInt64)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlMoney SqlMoney { get { if (StorageType.Money == _type) { if (IsNull) { return SqlMoney.Null; } return new SqlMoney(_value._int64, 1/*ignored*/); } return (SqlMoney)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlSingle SqlSingle { get { if (StorageType.Single == _type) { if (IsNull) { return SqlSingle.Null; } return new SqlSingle(_value._single); } return (SqlSingle)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlString SqlString { get { if (StorageType.String == _type) { if (IsNull) { return SqlString.Null; } return new SqlString((String)_object); } else if (StorageType.SqlCachedBuffer == _type) { SqlCachedBuffer data = (SqlCachedBuffer)(_object); if (data.IsNull) { return SqlString.Null; } return data.ToSqlString(); } return (SqlString)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal object SqlValue { get { switch (_type) { case StorageType.Empty: return DBNull.Value; case StorageType.Boolean: return SqlBoolean; case StorageType.Byte: return SqlByte; case StorageType.DateTime: return SqlDateTime; case StorageType.Decimal: return SqlDecimal; case StorageType.Double: return SqlDouble; case StorageType.Int16: return SqlInt16; case StorageType.Int32: return SqlInt32; case StorageType.Int64: return SqlInt64; case StorageType.Money: return SqlMoney; case StorageType.Single: return SqlSingle; case StorageType.String: return SqlString; case StorageType.SqlCachedBuffer: { SqlCachedBuffer data = (SqlCachedBuffer)(_object); if (data.IsNull) { return SqlXml.Null; } return data.ToSqlXml(); } case StorageType.SqlBinary: case StorageType.SqlGuid: return _object; case StorageType.SqlXml: { if (_isNull) { return SqlXml.Null; } Debug.Assert(null != _object); return (SqlXml) _object; } case StorageType.Date: case StorageType.DateTime2: if (_isNull) { return DBNull.Value; } return DateTime; case StorageType.DateTimeOffset: if (_isNull) { return DBNull.Value; } return DateTimeOffset; case StorageType.Time: if (_isNull) { return DBNull.Value; } return Time; } return null; // need to return the value as an object of some SQL type } } internal object Value { get { if (IsNull) { return DBNull.Value; } switch (_type) { case StorageType.Empty: return DBNull.Value; case StorageType.Boolean: return Boolean; case StorageType.Byte: return Byte; case StorageType.DateTime: return DateTime; case StorageType.Decimal: return Decimal; case StorageType.Double: return Double; case StorageType.Int16: return Int16; case StorageType.Int32: return Int32; case StorageType.Int64: return Int64; case StorageType.Money: return Decimal; case StorageType.Single: return Single; case StorageType.String: return String; case StorageType.SqlBinary: return ByteArray; case StorageType.SqlCachedBuffer: { // If we have a CachedBuffer, it's because it's an XMLTYPE column // and we have to return a string when they're asking for the CLS // value of the column. return ((SqlCachedBuffer)(_object)).ToString(); } case StorageType.SqlGuid: return Guid; case StorageType.SqlXml: { // XMLTYPE columns must be returned as string when asking for the CLS value SqlXml data = (SqlXml)_object; string s = data.Value; return s; } case StorageType.Date: return DateTime; case StorageType.DateTime2: return DateTime; case StorageType.DateTimeOffset: return DateTimeOffset; case StorageType.Time: return Time; } return null; // need to return the value as an object of some CLS type } } internal Type GetTypeFromStorageType (bool isSqlType) { if (isSqlType) { switch (_type) { case SqlBuffer.StorageType.Empty: return null; case SqlBuffer.StorageType.Boolean: return typeof(SqlBoolean); case SqlBuffer.StorageType.Byte: return typeof(SqlByte); case SqlBuffer.StorageType.DateTime: return typeof(SqlDateTime); case SqlBuffer.StorageType.Decimal: return typeof(SqlDecimal); case SqlBuffer.StorageType.Double: return typeof(SqlDouble); case SqlBuffer.StorageType.Int16: return typeof(SqlInt16); case SqlBuffer.StorageType.Int32: return typeof(SqlInt32); case SqlBuffer.StorageType.Int64: return typeof(SqlInt64); case SqlBuffer.StorageType.Money: return typeof(SqlMoney); case SqlBuffer.StorageType.Single: return typeof(SqlSingle); case SqlBuffer.StorageType.String: return typeof(SqlString); case SqlBuffer.StorageType.SqlCachedBuffer: return typeof(SqlString); case SqlBuffer.StorageType.SqlBinary: return typeof(object); case SqlBuffer.StorageType.SqlGuid: return typeof(object); case SqlBuffer.StorageType.SqlXml: return typeof(SqlXml); } } else { //Is CLR Type switch (_type) { case SqlBuffer.StorageType.Empty: return null; case SqlBuffer.StorageType.Boolean: return typeof(Boolean); case SqlBuffer.StorageType.Byte: return typeof(Byte); case SqlBuffer.StorageType.DateTime: return typeof(DateTime); case SqlBuffer.StorageType.Decimal: return typeof(Decimal); case SqlBuffer.StorageType.Double: return typeof(Double); case SqlBuffer.StorageType.Int16: return typeof(Int16); case SqlBuffer.StorageType.Int32: return typeof(Int32); case SqlBuffer.StorageType.Int64: return typeof(Int64); case SqlBuffer.StorageType.Money: return typeof(Decimal); case SqlBuffer.StorageType.Single: return typeof(Single); case SqlBuffer.StorageType.String: return typeof(String); case SqlBuffer.StorageType.SqlBinary: return typeof(Byte[]); case SqlBuffer.StorageType.SqlCachedBuffer: return typeof(string); case SqlBuffer.StorageType.SqlGuid: return typeof(Guid); case SqlBuffer.StorageType.SqlXml: return typeof(string); } } return null; // need to return the value as an object of some CLS type } internal static SqlBuffer[] CreateBufferArray(int length) { SqlBuffer[] buffers = new SqlBuffer[length]; for(int i = 0; i < buffers.Length; ++i) { buffers[i] = new SqlBuffer(); } return buffers; } internal static SqlBuffer[] CloneBufferArray(SqlBuffer[] values) { SqlBuffer[] copy = new SqlBuffer[values.Length]; for (int i=0; i<values.Length; i++) { copy[i] = new SqlBuffer(values[i]); } return copy; } internal static void Clear(SqlBuffer[] values) { if (null != values) { for(int i = 0; i < values.Length; ++i) { values[i].Clear(); } } } internal void Clear() { _isNull = false; _type = StorageType.Empty; _object = null; } internal void SetToDateTime(int daypart, int timepart) { Debug.Assert (IsEmpty, "setting value a second time?"); _value._dateTimeInfo.daypart = daypart; _value._dateTimeInfo.timepart = timepart; _type = StorageType.DateTime; _isNull = false; } internal void SetToDecimal(byte precision, byte scale, bool positive, int[] bits) { Debug.Assert (IsEmpty, "setting value a second time?"); _value._numericInfo.precision = precision; _value._numericInfo.scale = scale; _value._numericInfo.positive = positive; _value._numericInfo.data1 = bits[0]; _value._numericInfo.data2 = bits[1]; _value._numericInfo.data3 = bits[2]; _value._numericInfo.data4 = bits[3]; _type = StorageType.Decimal; _isNull = false; } internal void SetToMoney(long value) { Debug.Assert (IsEmpty, "setting value a second time?"); _value._int64 = value; _type = StorageType.Money; _isNull = false; } internal void SetToNullOfType(StorageType storageType) { Debug.Assert (IsEmpty, "setting value a second time?"); _type = storageType; _isNull = true; _object = null; } internal void SetToString(string value) { Debug.Assert (IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.String; _isNull = false; } internal void SetToDate(byte[] bytes) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.Date; _value._int32 = GetDateFromByteArray(bytes, 0); _isNull = false; } internal void SetToDate(DateTime date) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.Date; _value._int32 = date.Subtract(DateTime.MinValue).Days; _isNull = false; } internal void SetToTime(byte[] bytes, int length, byte scale, byte denormalizedScale) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.Time; FillInTimeInfo(ref _value._timeInfo, bytes, length, scale, denormalizedScale); _isNull = false; } internal void SetToTime(TimeSpan timeSpan, byte scale) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.Time; _value._timeInfo.ticks = timeSpan.Ticks; _value._timeInfo.scale = scale; _isNull = false; } internal void SetToDateTime2(byte[] bytes, int length, byte scale, byte denormalizedScale) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.DateTime2; FillInTimeInfo(ref _value._dateTime2Info.timeInfo, bytes, length - 3, scale, denormalizedScale); // remaining 3 bytes is for date _value._dateTime2Info.date = GetDateFromByteArray(bytes, length - 3); // 3 bytes for date _isNull = false; } internal void SetToDateTime2(DateTime dateTime, byte scale) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.DateTime2; _value._dateTime2Info.timeInfo.ticks = dateTime.TimeOfDay.Ticks; _value._dateTime2Info.timeInfo.scale = scale; _value._dateTime2Info.date = dateTime.Subtract(DateTime.MinValue).Days; _isNull = false; } internal void SetToDateTimeOffset(byte[] bytes, int length, byte scale, byte denormalizedScale) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.DateTimeOffset; FillInTimeInfo(ref _value._dateTimeOffsetInfo.dateTime2Info.timeInfo, bytes, length - 5, scale, denormalizedScale); // remaining 5 bytes are for date and offset _value._dateTimeOffsetInfo.dateTime2Info.date = GetDateFromByteArray(bytes, length - 5); // 3 bytes for date _value._dateTimeOffsetInfo.offset = (Int16)(bytes[length - 2] + (bytes[length - 1] << 8)); // 2 bytes for offset (Int16) _isNull = false; } internal void SetToDateTimeOffset(DateTimeOffset dateTimeOffset, byte scale) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.DateTimeOffset; DateTime utcDateTime = dateTimeOffset.UtcDateTime; // timeInfo stores the utc datetime of a datatimeoffset _value._dateTimeOffsetInfo.dateTime2Info.timeInfo.ticks = utcDateTime.TimeOfDay.Ticks; _value._dateTimeOffsetInfo.dateTime2Info.timeInfo.scale = scale; _value._dateTimeOffsetInfo.dateTime2Info.date = utcDateTime.Subtract(DateTime.MinValue).Days; _value._dateTimeOffsetInfo.offset = (Int16)dateTimeOffset.Offset.TotalMinutes; _isNull = false; } private static void FillInTimeInfo(ref TimeInfo timeInfo, byte[] timeBytes, int length, byte scale, byte denormalizedScale) { Debug.Assert(3 <= length && length <= 5, "invalid data length for timeInfo: " + length); Debug.Assert(0 <= scale && scale <= 7, "invalid scale: " + scale); Debug.Assert(0 <= denormalizedScale && denormalizedScale <= 7, "invalid denormalized scale: " + denormalizedScale); Int64 tickUnits = (Int64)timeBytes[0] + ((Int64)timeBytes[1] << 8) + ((Int64)timeBytes[2] << 16); if (length > 3) { tickUnits += ((Int64)timeBytes[3] << 24); } if (length > 4) { tickUnits += ((Int64)timeBytes[4] << 32); } timeInfo.ticks = tickUnits * TdsEnums.TICKS_FROM_SCALE[scale]; // Once the deserialization has been completed using the value scale, we need to set the actual denormalized scale, // coming from the data type, on the original result, so that it has the proper scale setting. // This only applies for values that got serialized/deserialized for encryption. Otherwise, both scales should be equal. timeInfo.scale = denormalizedScale; } private static Int32 GetDateFromByteArray(byte[] buf, int offset) { return buf[offset] + (buf[offset + 1] << 8) + (buf[offset + 2] << 16); } private void ThrowIfNull() { if (IsNull) { throw new SqlNullValueException(); } } } }// namespace
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System { // DateTimeOffset is a value type that consists of a DateTime and a time zone offset, // ie. how far away the time is from GMT. The DateTime is stored whole, and the offset // is stored as an Int16 internally to save space, but presented as a TimeSpan. // // The range is constrained so that both the represented clock time and the represented // UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime // for actual UTC times, and a slightly constrained range on one end when an offset is // present. // // This class should be substitutable for date time in most cases; so most operations // effectively work on the clock time. However, the underlying UTC time is what counts // for the purposes of identity, sorting and subtracting two instances. // // // There are theoretically two date times stored, the UTC and the relative local representation // or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable // for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this // out and for internal readability. [StructLayout(LayoutKind.Auto)] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct DateTimeOffset : IComparable, IFormattable, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>, ISerializable, IDeserializationCallback, ISpanFormattable { // Constants internal const long MaxOffset = TimeSpan.TicksPerHour * 14; internal const long MinOffset = -MaxOffset; private const long UnixEpochSeconds = DateTime.UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 private const long UnixEpochMilliseconds = DateTime.UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 internal const long UnixMinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; internal const long UnixMaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; // Static Fields public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero); public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero); public static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(DateTime.UnixEpochTicks, TimeSpan.Zero); // Instance Fields private readonly DateTime _dateTime; private readonly short _offsetMinutes; // Constructors // Constructs a DateTimeOffset from a tick count and offset public DateTimeOffset(long ticks, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); // Let the DateTime constructor do the range checks DateTime dateTime = new DateTime(ticks); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds, // extracts the local offset. For UTC, creates a UTC instance with a zero offset. public DateTimeOffset(DateTime dateTime) { TimeSpan offset; if (dateTime.Kind != DateTimeKind.Utc) { // Local and Unspecified are both treated as Local offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else { offset = new TimeSpan(0); } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time // consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that // the offset corresponds to the local. public DateTimeOffset(DateTime dateTime, TimeSpan offset) { if (dateTime.Kind == DateTimeKind.Local) { if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) { throw new ArgumentException(SR.Argument_OffsetLocalMismatch, nameof(offset)); } } else if (dateTime.Kind == DateTimeKind.Utc) { if (offset != TimeSpan.Zero) { throw new ArgumentException(SR.Argument_OffsetUtcMismatch, nameof(offset)); } } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); int originalSecond = second; if (second == 60 && DateTime.s_systemSupportsLeapSeconds) { // Reset the leap second to 59 for now and then we'll validate it after getting the final UTC time. second = 59; } _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset); if (originalSecond == 60 && !DateTime.IsValidTimeWithLeapSeconds(_dateTime.Year, _dateTime.Month, _dateTime.Day, _dateTime.Hour, _dateTime.Minute, 60, DateTimeKind.Utc)) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond and offset public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); int originalSecond = second; if (second == 60 && DateTime.s_systemSupportsLeapSeconds) { // Reset the leap second to 59 for now and then we'll validate it after getting the final UTC time. second = 59; } _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset); if (originalSecond == 60 && !DateTime.IsValidTimeWithLeapSeconds(_dateTime.Year, _dateTime.Month, _dateTime.Day, _dateTime.Hour, _dateTime.Minute, 60, DateTimeKind.Utc)) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond, Calendar and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); int originalSecond = second; if (second == 60 && DateTime.s_systemSupportsLeapSeconds) { // Reset the leap second to 59 for now and then we'll validate it after getting the final UTC time. second = 59; } _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset); if (originalSecond == 60 && !DateTime.IsValidTimeWithLeapSeconds(_dateTime.Year, _dateTime.Month, _dateTime.Day, _dateTime.Hour, _dateTime.Minute, 60, DateTimeKind.Utc)) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } } // Returns a DateTimeOffset representing the current date and time. The // resolution of the returned value depends on the system timer. public static DateTimeOffset Now { get { return new DateTimeOffset(DateTime.Now); } } public static DateTimeOffset UtcNow { get { return new DateTimeOffset(DateTime.UtcNow); } } public DateTime DateTime { get { return ClockDateTime; } } public DateTime UtcDateTime { get { return DateTime.SpecifyKind(_dateTime, DateTimeKind.Utc); } } public DateTime LocalDateTime { get { return UtcDateTime.ToLocalTime(); } } // Adjust to a given offset with the same UTC time. Can throw ArgumentException // public DateTimeOffset ToOffset(TimeSpan offset) { return new DateTimeOffset((_dateTime + offset).Ticks, offset); } // Instance Properties // The clock or visible time represented. This is just a wrapper around the internal date because this is // the chosen storage mechanism. Going through this helper is good for readability and maintainability. // This should be used for display but not identity. private DateTime ClockDateTime { get { return new DateTime((_dateTime + Offset).Ticks, DateTimeKind.Unspecified); } } // Returns the date part of this DateTimeOffset. The resulting value // corresponds to this DateTimeOffset with the time-of-day part set to // zero (midnight). // public DateTime Date { get { return ClockDateTime.Date; } } // Returns the day-of-month part of this DateTimeOffset. The returned // value is an integer between 1 and 31. // public int Day { get { return ClockDateTime.Day; } } // Returns the day-of-week part of this DateTimeOffset. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek DayOfWeek { get { return ClockDateTime.DayOfWeek; } } // Returns the day-of-year part of this DateTimeOffset. The returned value // is an integer between 1 and 366. // public int DayOfYear { get { return ClockDateTime.DayOfYear; } } // Returns the hour part of this DateTimeOffset. The returned value is an // integer between 0 and 23. // public int Hour { get { return ClockDateTime.Hour; } } // Returns the millisecond part of this DateTimeOffset. The returned value // is an integer between 0 and 999. // public int Millisecond { get { return ClockDateTime.Millisecond; } } // Returns the minute part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Minute { get { return ClockDateTime.Minute; } } // Returns the month part of this DateTimeOffset. The returned value is an // integer between 1 and 12. // public int Month { get { return ClockDateTime.Month; } } public TimeSpan Offset { get { return new TimeSpan(0, _offsetMinutes, 0); } } // Returns the second part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Second { get { return ClockDateTime.Second; } } // Returns the tick count for this DateTimeOffset. The returned value is // the number of 100-nanosecond intervals that have elapsed since 1/1/0001 // 12:00am. // public long Ticks { get { return ClockDateTime.Ticks; } } public long UtcTicks { get { return UtcDateTime.Ticks; } } // Returns the time-of-day part of this DateTimeOffset. The returned value // is a TimeSpan that indicates the time elapsed since midnight. // public TimeSpan TimeOfDay { get { return ClockDateTime.TimeOfDay; } } // Returns the year part of this DateTimeOffset. The returned value is an // integer between 1 and 9999. // public int Year { get { return ClockDateTime.Year; } } // Returns the DateTimeOffset resulting from adding the given // TimeSpan to this DateTimeOffset. // public DateTimeOffset Add(TimeSpan timeSpan) { return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // days to this DateTimeOffset. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddDays(double days) { return new DateTimeOffset(ClockDateTime.AddDays(days), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // hours to this DateTimeOffset. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddHours(double hours) { return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset); } // Returns the DateTimeOffset resulting from the given number of // milliseconds to this DateTimeOffset. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to this DateTimeOffset. The value // argument is permitted to be negative. // public DateTimeOffset AddMilliseconds(double milliseconds) { return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // minutes to this DateTimeOffset. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddMinutes(double minutes) { return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset); } public DateTimeOffset AddMonths(int months) { return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // seconds to this DateTimeOffset. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddSeconds(double seconds) { return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // 100-nanosecond ticks to this DateTimeOffset. The value argument // is permitted to be negative. // public DateTimeOffset AddTicks(long ticks) { return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // years to this DateTimeOffset. The result is computed by incrementing // (or decrementing) the year part of this DateTimeOffset by value // years. If the month and day of this DateTimeOffset is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of this DateTimeOffset. // public DateTimeOffset AddYears(int years) { return new DateTimeOffset(ClockDateTime.AddYears(years), Offset); } // Compares two DateTimeOffset values, returning an integer that indicates // their relationship. // public static int Compare(DateTimeOffset first, DateTimeOffset second) { return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); } // Compares this DateTimeOffset to a given object. This method provides an // implementation of the IComparable interface. The object // argument must be another DateTimeOffset, or otherwise an exception // occurs. Null is considered less than any instance. // int IComparable.CompareTo(object obj) { if (obj == null) return 1; if (!(obj is DateTimeOffset)) { throw new ArgumentException(SR.Arg_MustBeDateTimeOffset); } DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime; DateTime utc = UtcDateTime; if (utc > objUtc) return 1; if (utc < objUtc) return -1; return 0; } public int CompareTo(DateTimeOffset other) { DateTime otherUtc = other.UtcDateTime; DateTime utc = UtcDateTime; if (utc > otherUtc) return 1; if (utc < otherUtc) return -1; return 0; } // Checks if this DateTimeOffset is equal to a given object. Returns // true if the given object is a boxed DateTimeOffset and its value // is equal to the value of this DateTimeOffset. Returns false // otherwise. // public override bool Equals(object obj) { if (obj is DateTimeOffset) { return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime); } return false; } public bool Equals(DateTimeOffset other) { return UtcDateTime.Equals(other.UtcDateTime); } public bool EqualsExact(DateTimeOffset other) { // // returns true when the ClockDateTime, Kind, and Offset match // // currently the Kind should always be Unspecified, but there is always the possibility that a future version // of DateTimeOffset overloads the Kind field // return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind); } // Compares two DateTimeOffset values for equality. Returns true if // the two DateTimeOffset values are equal, or false if they are // not equal. // public static bool Equals(DateTimeOffset first, DateTimeOffset second) { return DateTime.Equals(first.UtcDateTime, second.UtcDateTime); } // Creates a DateTimeOffset from a Windows filetime. A Windows filetime is // a long representing the date and time as the number of // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am. // public static DateTimeOffset FromFileTime(long fileTime) { return new DateTimeOffset(DateTime.FromFileTime(fileTime)); } public static DateTimeOffset FromUnixTimeSeconds(long seconds) { if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) { throw new ArgumentOutOfRangeException(nameof(seconds), SR.Format(SR.ArgumentOutOfRange_Range, UnixMinSeconds, UnixMaxSeconds)); } long ticks = seconds * TimeSpan.TicksPerSecond + DateTime.UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) { const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) { throw new ArgumentOutOfRangeException(nameof(milliseconds), SR.Format(SR.ArgumentOutOfRange_Range, MinMilliseconds, MaxMilliseconds)); } long ticks = milliseconds * TimeSpan.TicksPerMillisecond + DateTime.UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } // ----- SECTION: private serialization instance methods ----------------* void IDeserializationCallback.OnDeserialization(object sender) { try { ValidateOffset(Offset); ValidateDate(ClockDateTime, Offset); } catch (ArgumentException e) { throw new SerializationException(SR.Serialization_InvalidData, e); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue("DateTime", _dateTime); // Do not rename (binary serialization) info.AddValue("OffsetMinutes", _offsetMinutes); // Do not rename (binary serialization) } private DateTimeOffset(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); // Do not rename (binary serialization) _offsetMinutes = (short)info.GetValue("OffsetMinutes", typeof(short)); // Do not rename (binary serialization) } // Returns the hash code for this DateTimeOffset. // public override int GetHashCode() { return UtcDateTime.GetHashCode(); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(string input) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(string input, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return Parse(input, formatProvider, DateTimeStyles.None); } public static DateTimeOffset Parse(string input, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider = null, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(string input, string format, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return ParseExact(input, format, formatProvider, DateTimeStyles.None); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(string input, string format, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); return new DateTimeOffset(dateResult.Ticks, offset); } public TimeSpan Subtract(DateTimeOffset value) { return UtcDateTime.Subtract(value.UtcDateTime); } public DateTimeOffset Subtract(TimeSpan value) { return new DateTimeOffset(ClockDateTime.Subtract(value), Offset); } public long ToFileTime() { return UtcDateTime.ToFileTime(); } public long ToUnixTimeSeconds() { // Truncate sub-second precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times. // // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0 // ticks = 621355967990010000 // ticksFromEpoch = ticks - DateTime.UnixEpochTicks = -9990000 // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0 // // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division, // whereas we actually always want to round *down* when converting to Unix time. This happens // automatically for positive Unix time values. Now the example becomes: // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799 // secondsFromEpoch = seconds - UnixEpochSeconds = -1 // // In other words, we want to consistently round toward the time 1/1/0001 00:00:00, // rather than toward the Unix Epoch (1/1/1970 00:00:00). long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond; return seconds - UnixEpochSeconds; } public long ToUnixTimeMilliseconds() { // Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond; return milliseconds - UnixEpochMilliseconds; } public DateTimeOffset ToLocalTime() { return ToLocalTime(false); } internal DateTimeOffset ToLocalTime(bool throwOnOverflow) { return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow)); } public override string ToString() { return DateTimeFormat.Format(ClockDateTime, null, null, Offset); } public string ToString(string format) { return DateTimeFormat.Format(ClockDateTime, format, null, Offset); } public string ToString(IFormatProvider formatProvider) { return DateTimeFormat.Format(ClockDateTime, null, formatProvider, Offset); } public string ToString(string format, IFormatProvider formatProvider) { return DateTimeFormat.Format(ClockDateTime, format, formatProvider, Offset); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider formatProvider = null) => DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, formatProvider, Offset); public DateTimeOffset ToUniversalTime() { return new DateTimeOffset(UtcDateTime); } public static bool TryParse(string input, out DateTimeOffset result) { TimeSpan offset; DateTime dateResult; bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParse(ReadOnlySpan<char> input, out DateTimeOffset result) { bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out DateTime dateResult, out TimeSpan offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParse(string input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) { result = default; return false; } TimeSpan offset; DateTime dateResult; bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null || format == null) { result = default; return false; } TimeSpan offset; DateTime dateResult; bool parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParseExact( ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) { result = default; return false; } TimeSpan offset; DateTime dateResult; bool parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static bool TryParseExact( ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } // Ensures the TimeSpan is valid to go in a DateTimeOffset. private static short ValidateOffset(TimeSpan offset) { long ticks = offset.Ticks; if (ticks % TimeSpan.TicksPerMinute != 0) { throw new ArgumentException(SR.Argument_OffsetPrecision, nameof(offset)); } if (ticks < MinOffset || ticks > MaxOffset) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_OffsetOutOfRange); } return (short)(offset.Ticks / TimeSpan.TicksPerMinute); } // Ensures that the time and offset are in range. private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) { // The key validation is that both the UTC and clock times fit. The clock time is validated // by the DateTime constructor. Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated."); // This operation cannot overflow because offset should have already been validated to be within // 14 hours and the DateTime instance is more than that distance from the boundaries of long. long utcTicks = dateTime.Ticks - offset.Ticks; if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_UTCOutOfRange); } // make sure the Kind is set to Unspecified // return new DateTime(utcTicks, DateTimeKind.Unspecified); } private static DateTimeStyles ValidateStyles(DateTimeStyles style, string parameterName) { if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidDateTimeStyles, parameterName); } if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) { throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName); } if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) { throw new ArgumentException(SR.Argument_DateTimeOffsetInvalidDateTimeStyles, parameterName); } // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime style &= ~DateTimeStyles.RoundtripKind; // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse style &= ~DateTimeStyles.AssumeLocal; return style; } // Operators public static implicit operator DateTimeOffset(DateTime dateTime) { return new DateTimeOffset(dateTime); } public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset); } public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset); } public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime - right.UtcDateTime; } public static bool operator ==(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime == right.UtcDateTime; } public static bool operator !=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime != right.UtcDateTime; } public static bool operator <(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime < right.UtcDateTime; } public static bool operator <=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime <= right.UtcDateTime; } public static bool operator >(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime > right.UtcDateTime; } public static bool operator >=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime >= right.UtcDateTime; } } }
/*************************************************************************** * SafeUri.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <[email protected]> ****************************************************************************/ /* 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.Runtime.InteropServices; namespace Hyena { public class SafeUri { private enum LocalPathCheck { NotPerformed, Yes, No } private static int MAX_SCHEME_LENGTH = 8; private string uri; private string local_path; private string scheme; private LocalPathCheck local_path_check = LocalPathCheck.NotPerformed; public SafeUri (string uri) { int scheme_delimit_index = uri.IndexOf ("://", StringComparison.InvariantCulture); if (scheme_delimit_index > 0 && scheme_delimit_index <= MAX_SCHEME_LENGTH) { this.uri = uri; } else { this.uri = FilenameToUri (uri); } } public SafeUri (string uri, bool isUri) { if (isUri) { this.uri = uri; } else { this.uri = FilenameToUri (uri); } } public SafeUri (Uri uri) { this.uri = uri.AbsoluteUri; } public static string FilenameToUri (string localPath) { // TODO: replace with managed conversion to avoid marshalling IntPtr path_ptr = GLib.Marshaller.StringToPtrGStrdup (localPath); IntPtr uri_ptr = PlatformDetection.IsWindows ? g_filename_to_uri_utf8 (path_ptr, IntPtr.Zero, IntPtr.Zero) : g_filename_to_uri (path_ptr, IntPtr.Zero, IntPtr.Zero); GLib.Marshaller.Free (path_ptr); if (uri_ptr == IntPtr.Zero) { throw new ApplicationException ("Filename path must be absolute"); } string uri = GLib.Marshaller.Utf8PtrToString (uri_ptr); GLib.Marshaller.Free (uri_ptr); return uri; } public static string UriToFilename (string uri) { // TODO: replace with managed conversion to avoid marshalling IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri); IntPtr path_ptr = PlatformDetection.IsWindows ? g_filename_from_uri_utf8 (uri_ptr, IntPtr.Zero, IntPtr.Zero) : g_filename_from_uri (uri_ptr, IntPtr.Zero, IntPtr.Zero); GLib.Marshaller.Free (uri_ptr); if (path_ptr == IntPtr.Zero) { throw new ApplicationException ("URI could not be converted to local file location"); } string path = GLib.Marshaller.Utf8PtrToString (path_ptr); GLib.Marshaller.Free (path_ptr); return path; } public static string UriToFilename (SafeUri uri) { return UriToFilename (uri.AbsoluteUri); } public override string ToString () { return AbsoluteUri; } public static implicit operator string (SafeUri s) { return s.ToString (); } public override bool Equals (object o) { SafeUri s = o as SafeUri; if (s != null) { return s.AbsoluteUri == AbsoluteUri; } return false; } public override int GetHashCode () { return AbsoluteUri.GetHashCode (); } public string AbsoluteUri { get { return uri; } } public bool IsLocalPath { get { if (local_path_check == LocalPathCheck.NotPerformed) { if (IsFile) { local_path_check = LocalPathCheck.Yes; return true; } else { local_path_check = LocalPathCheck.No; return false; } } return local_path_check == LocalPathCheck.Yes; } } public string AbsolutePath { get { if (local_path == null && IsLocalPath) { local_path = UriToFilename (uri); } return local_path; } } public string LocalPath { get { return AbsolutePath; } } public string Scheme { get { if (scheme == null) { scheme = uri.Substring (0, uri.IndexOf ("://", StringComparison.InvariantCulture)); } return scheme; } } public bool IsFile { get { return Scheme == System.Uri.UriSchemeFile; } } [DllImport ("libglib-2.0-0.dll")] private static extern IntPtr g_filename_to_uri_utf8 (IntPtr filename, IntPtr hostname, IntPtr error); [DllImport ("libglib-2.0-0.dll")] private static extern IntPtr g_filename_from_uri_utf8 (IntPtr uri, IntPtr hostname, IntPtr error); [DllImport ("libglib-2.0-0.dll")] private static extern IntPtr g_filename_to_uri (IntPtr filename, IntPtr hostname, IntPtr error); [DllImport ("libglib-2.0-0.dll")] private static extern IntPtr g_filename_from_uri (IntPtr uri, IntPtr hostname, IntPtr error); } }
// 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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedDivideNullableTests { #region Test methods [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableByte(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableFloat(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableInt(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableLong(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableSByte(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableShort(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUInt(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableULong(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUShort(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableNumberTest(bool useInterpreter) { Number?[] values = new Number?[] { null, new Number(0), new Number(1), Number.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableNumber(values[i], values[j], useInterpreter); } } } #endregion #region Helpers public static byte DivideNullableByte(byte a, byte b) { return (byte)(a / b); } public static char DivideNullableChar(char a, char b) { return (char)(a / b); } public static decimal DivideNullableDecimal(decimal a, decimal b) { return (decimal)(a / b); } public static double DivideNullableDouble(double a, double b) { return (double)(a / b); } public static float DivideNullableFloat(float a, float b) { return (float)(a / b); } public static int DivideNullableInt(int a, int b) { return (int)(a / b); } public static long DivideNullableLong(long a, long b) { return (long)(a / b); } public static sbyte DivideNullableSByte(sbyte a, sbyte b) { return unchecked((sbyte)(a / b)); } public static short DivideNullableShort(short a, short b) { return unchecked((short)(a / b)); } public static uint DivideNullableUInt(uint a, uint b) { return (uint)(a / b); } public static ulong DivideNullableULong(ulong a, ulong b) { return (ulong)(a / b); } public static ushort DivideNullableUShort(ushort a, ushort b) { return (ushort)(a / b); } #endregion #region Test verifiers private static void VerifyDivideNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Divide( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableByte"))); Func<byte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((byte?)(a / b), f()); } private static void VerifyDivideNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Divide( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableChar"))); Func<char?> f = e.Compile(useInterpreter); if (a.HasValue && b == '\0') Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((char?)(a / b), f()); } private static void VerifyDivideNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Divide( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableDecimal"))); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Divide( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableDouble"))); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDivideNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Divide( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableFloat"))); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDivideNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Divide( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableInt"))); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == int.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Divide( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableLong"))); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == long.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Divide( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableSByte"))); Func<sbyte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(unchecked((sbyte?)(a / b)), f()); } private static void VerifyDivideNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Divide( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableShort"))); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(unchecked((short?)(a / b)), f()); } private static void VerifyDivideNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Divide( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableUInt"))); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Divide( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableULong"))); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Divide( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableUShort"))); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((ushort?)(a / b), f()); } private static void VerifyDivideNullableNumber(Number? a, Number? b, bool useInterpreter) { Expression<Func<Number?>> e = Expression.Lambda<Func<Number?>>( Expression.Divide( Expression.Constant(a, typeof(Number?)), Expression.Constant(b, typeof(Number?)))); Assert.Equal(typeof(Number?), e.Body.Type); Func<Number?> f = e.Compile(useInterpreter); if (a.HasValue && b == new Number(0)) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using log4net; using PacketDotNet.MiscUtil.Conversion; using PacketDotNet.Utils; namespace PacketDotNet { /// <summary> /// IPv6 packet /// References /// ---------- /// http://tools.ietf.org/html/rfc2460 /// http://en.wikipedia.org/wiki/IPv6 /// </summary> public class IPv6Packet : IpPacket { #if DEBUG private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #else // NOTE: No need to warn about lack of use, the compiler won't // put any calls to 'log' here but we need 'log' to exist to compile #pragma warning disable 0169, 0649 private static readonly ILogInactive log; #pragma warning restore 0169, 0649 #endif /// <value> /// Minimum number of bytes in an IPv6 header /// </value> public const int HeaderMinimumLength = 40; /// <value> /// The version of the IP protocol. The '6' in IPv6 indicates the version of the protocol /// </value> public static IpVersion ipVersion = IpVersion.IPv6; private Int32 VersionTrafficClassFlowLabel { get { return EndianBitConverter.Big.ToInt32(this.header.Bytes, this.header.Offset + IPv6Fields.VersionTrafficClassFlowLabelPosition); } set { EndianBitConverter.Big.CopyBytes(value, this.header.Bytes, this.header.Offset + IPv6Fields.VersionTrafficClassFlowLabelPosition); } } /// <summary> /// The version field of the IPv6 Packet. /// </summary> public override IpVersion Version { get { return (IpVersion) ((this.VersionTrafficClassFlowLabel >> 28)&0xF); } set { var theValue = (Int32) value; // read the existing value var field = (UInt32) this.VersionTrafficClassFlowLabel; // mask the new field into place field = (UInt32) ((field&0x0FFFFFFF)|((theValue << 28)&0xF0000000)); // write the updated value back this.VersionTrafficClassFlowLabel = (int) field; } } /// <summary> /// The traffic class field of the IPv6 Packet. /// </summary> public virtual int TrafficClass { get { return ((this.VersionTrafficClassFlowLabel >> 20)&0xFF); } set { // read the original value var field = (UInt32) this.VersionTrafficClassFlowLabel; // mask in the new field field = (field&0xF00FFFFF)|(((UInt32) value) << 20)&0x0FF00000; // write the updated value back this.VersionTrafficClassFlowLabel = (int) field; } } /// <summary> /// The flow label field of the IPv6 Packet. /// </summary> public virtual int FlowLabel { get { return (this.VersionTrafficClassFlowLabel&0xFFFFF); } set { // read the original value var field = (UInt32) this.VersionTrafficClassFlowLabel; // make the value in field = (field&0xFFF00000)|((UInt32) (value)&0x000FFFFF); // write the updated value back this.VersionTrafficClassFlowLabel = (int) field; } } /// <summary> /// The payload lengeth field of the IPv6 Packet /// NOTE: Differs from the IPv4 'Total length' field that includes the length of the header as /// payload length is ONLY the size of the payload. /// </summary> public override ushort PayloadLength { get { return EndianBitConverter.Big.ToUInt16(this.header.Bytes, this.header.Offset + IPv6Fields.PayloadLengthPosition); } set { EndianBitConverter.Big.CopyBytes(value, this.header.Bytes, this.header.Offset + IPv6Fields.PayloadLengthPosition); } } /// <value> /// Backwards compatibility property for IPv4.HeaderLength /// NOTE: This field is the number of 32bit words /// </value> public override int HeaderLength { get { return (IPv6Fields.HeaderLength/4); } set { throw new NotImplementedException(); } } /// <value> /// Backwards compatibility property for IPv4.TotalLength /// </value> public override int TotalLength { get { return this.PayloadLength + (this.HeaderLength*4); } set { this.PayloadLength = (ushort) (value - (this.HeaderLength*4)); } } /// <summary> /// Identifies the protocol encapsulated by this packet /// Replaces IPv4's 'protocol' field, has compatible values /// </summary> public override IPProtocolType NextHeader { get { return (IPProtocolType) (this.header.Bytes[this.header.Offset + IPv6Fields.NextHeaderPosition]); } set { this.header.Bytes[this.header.Offset + IPv6Fields.NextHeaderPosition] = (byte) value; } } /// <value> /// The protocol of the packet encapsulated in this ip packet /// </value> public override IPProtocolType Protocol { get { return this.NextHeader; } set { this.NextHeader = value; } } /// <summary> /// The hop limit field of the IPv6 Packet. /// NOTE: Replaces the 'time to live' field of IPv4 /// 8-bit value /// </summary> public override int HopLimit { get { return this.header.Bytes[this.header.Offset + IPv6Fields.HopLimitPosition]; } set { this.header.Bytes[this.header.Offset + IPv6Fields.HopLimitPosition] = (byte) value; } } /// <value> /// Helper alias for 'HopLimit' /// </value> public override int TimeToLive { get { return this.HopLimit; } set { this.HopLimit = value; } } /// <summary> /// The source address field of the IPv6 Packet. /// </summary> public override IPAddress SourceAddress { get { return GetIPAddress(AddressFamily.InterNetworkV6, this.header.Offset + IPv6Fields.SourceAddressPosition, this.header.Bytes); } set { var address = value.GetAddressBytes(); Array.Copy(address, 0, this.header.Bytes, this.header.Offset + IPv6Fields.SourceAddressPosition, address.Length); } } /// <summary> /// The destination address field of the IPv6 Packet. /// </summary> public override IPAddress DestinationAddress { get { return GetIPAddress(AddressFamily.InterNetworkV6, this.header.Offset + IPv6Fields.DestinationAddressPosition, this.header.Bytes); } set { var address = value.GetAddressBytes(); Array.Copy(address, 0, this.header.Bytes, this.header.Offset + IPv6Fields.DestinationAddressPosition, address.Length); } } /// <summary> /// Create an IPv6 packet from values /// </summary> /// <param name="SourceAddress"> /// A <see cref="System.Net.IPAddress" /> /// </param> /// <param name="DestinationAddress"> /// A <see cref="System.Net.IPAddress" /> /// </param> public IPv6Packet(IPAddress SourceAddress, IPAddress DestinationAddress) { log.Debug(""); // allocate memory for this packet var offset = 0; var length = IPv6Fields.HeaderLength; var headerBytes = new byte[length]; this.header = new ByteArraySegment(headerBytes, offset, length); // set some default values to make this packet valid this.PayloadLength = 0; this.TimeToLive = this.DefaultTimeToLive; // set instance values this.SourceAddress = SourceAddress; this.DestinationAddress = DestinationAddress; this.Version = ipVersion; } /// <summary> /// Constructor /// </summary> /// <param name="bas"> /// A <see cref="ByteArraySegment" /> /// </param> public IPv6Packet(ByteArraySegment bas) { log.Debug(bas.ToString()); // slice off the header this.header = new ByteArraySegment(bas); this.header.Length = HeaderMinimumLength; // set the actual length, we need to do this because we need to set // header to something valid above before we can retrieve the PayloadLength log.DebugFormat("PayloadLength: {0}", this.PayloadLength); this.header.Length = bas.Length - this.PayloadLength; // parse the payload var payload = this.header.EncapsulatedBytes(this.PayloadLength); this.payloadPacketOrData = ParseEncapsulatedBytes(payload, this.NextHeader, this); } /// <summary> /// Prepend to the given byte[] origHeader the portion of the IPv6 header used for /// generating an tcp checksum /// http://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_checksum_using_IPv6 /// http://tools.ietf.org/html/rfc2460#page-27 /// </summary> /// <param name="origHeader"> /// A <see cref="System.Byte" /> /// </param> /// <returns> /// A <see cref="System.Byte" /> /// </returns> internal override byte[] AttachPseudoIPHeader(byte[] origHeader) { var ms = new MemoryStream(); var bw = new BinaryWriter(ms); // 0-16: ip src addr bw.Write(this.header.Bytes, this.header.Offset + IPv6Fields.SourceAddressPosition, IPv6Fields.AddressLength); // 17-32: ip dst addr bw.Write(this.header.Bytes, this.header.Offset + IPv6Fields.DestinationAddressPosition, IPv6Fields.AddressLength); // 33-36: TCP length bw.Write((UInt32) IPAddress.HostToNetworkOrder(origHeader.Length)); // 37-39: 3 bytes of zeros bw.Write((byte) 0); bw.Write((byte) 0); bw.Write((byte) 0); // 40: Next header bw.Write((byte) this.NextHeader); // prefix the pseudoHeader to the header+data var pseudoHeader = ms.ToArray(); var headerSize = pseudoHeader.Length + origHeader.Length; var odd = origHeader.Length%2 != 0; if(odd) { headerSize++; } var finalData = new byte[headerSize]; // copy the pseudo header in Array.Copy(pseudoHeader, 0, finalData, 0, pseudoHeader.Length); // copy the origHeader in Array.Copy(origHeader, 0, finalData, pseudoHeader.Length, origHeader.Length); //if not even length, pad with a zero if(odd) { finalData[finalData.Length - 1] = 0; } return finalData; } /// <summary cref="Packet.ToString(StringOutputType)" /> public override string ToString(StringOutputType outputFormat) { var buffer = new StringBuilder(); var color = ""; var colorEscape = ""; if(outputFormat == StringOutputType.Colored || outputFormat == StringOutputType.VerboseColored) { color = this.Color; colorEscape = AnsiEscapeSequences.Reset; } if(outputFormat == StringOutputType.Normal || outputFormat == StringOutputType.Colored) { // build the output string buffer.AppendFormat("{0}[IPv6Packet: SourceAddress={2}, DestinationAddress={3}, NextHeader={4}]{1}", color, colorEscape, this.SourceAddress, this.DestinationAddress, this.NextHeader); } if(outputFormat == StringOutputType.Verbose || outputFormat == StringOutputType.VerboseColored) { // collect the properties and their value var properties = new Dictionary<string, string>(); var ipVersion = Convert.ToString((int) this.Version, 2).PadLeft(4, '0'); properties.Add("version", ipVersion + " .... .... .... .... .... .... .... = " + (int) this.Version); var trafficClass = Convert.ToString(this.TrafficClass, 2).PadLeft(8, '0').Insert(4, " "); properties.Add("traffic class", ".... " + trafficClass + " .... .... .... .... .... = 0x" + this.TrafficClass.ToString("x").PadLeft(8, '0')); var flowLabel = Convert.ToString(this.FlowLabel, 2).PadLeft(20, '0').Insert(16, " ").Insert(12, " ").Insert(8, " ").Insert(4, " "); properties.Add("flow label", ".... .... .... " + flowLabel + " = 0x" + this.FlowLabel.ToString("x").PadLeft(8, '0')); properties.Add("payload length", this.PayloadLength.ToString()); properties.Add("next header", this.NextHeader + " (0x" + this.NextHeader.ToString("x") + ")"); properties.Add("hop limit", this.HopLimit.ToString()); properties.Add("source", this.SourceAddress.ToString()); properties.Add("destination", this.DestinationAddress.ToString()); // calculate the padding needed to right-justify the property names var padLength = RandomUtils.LongestStringLength(new List<string>(properties.Keys)); // build the output string buffer.AppendLine("IP: ******* IP - \"Internet Protocol (Version 6)\" - offset=? length=" + this.TotalPacketLength); buffer.AppendLine("IP:"); foreach(var property in properties) { if(property.Key.Trim() != "") { buffer.AppendLine("IP: " + property.Key.PadLeft(padLength) + " = " + property.Value); } else { buffer.AppendLine("IP: " + property.Key.PadLeft(padLength) + " " + property.Value); } } buffer.AppendLine("IP"); } // append the base class output buffer.Append(base.ToString(outputFormat)); return buffer.ToString(); } /// <summary> Fetch ascii escape sequence of the color associated with this packet type.</summary> public override String Color { get { return AnsiEscapeSequences.White; } } /// <summary> /// Generate a random packet /// </summary> /// <returns> /// A <see cref="Packet" /> /// </returns> public static IPv6Packet RandomPacket() { var srcAddress = RandomUtils.GetIPAddress(ipVersion); var dstAddress = RandomUtils.GetIPAddress(ipVersion); return new IPv6Packet(srcAddress, dstAddress); } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System.IO; using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.TestProtos; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Google.ProtocolBuffers { /// <summary> /// Miscellaneous tests for message operations that apply to both /// generated and dynamic messages. /// </summary> [TestClass] public class MessageTest { // ================================================================= // Message-merging tests. private static readonly TestAllTypes MergeSource = new TestAllTypes.Builder { OptionalInt32 = 1, OptionalString = "foo", OptionalForeignMessage = ForeignMessage.DefaultInstance, }.AddRepeatedString("bar").Build(); private static readonly TestAllTypes MergeDest = new TestAllTypes.Builder { OptionalInt64 = 2, OptionalString = "baz", OptionalForeignMessage = new ForeignMessage.Builder {C = 3}.Build(), }.AddRepeatedString("qux").Build(); private const string MergeResultText = "optional_int32: 1\n" + "optional_int64: 2\n" + "optional_string: \"foo\"\n" + "optional_foreign_message {\n" + " c: 3\n" + "}\n" + "repeated_string: \"qux\"\n" + "repeated_string: \"bar\"\n"; [TestMethod] public void MergeFrom() { TestAllTypes result = TestAllTypes.CreateBuilder(MergeDest).MergeFrom(MergeSource).Build(); Assert.AreEqual(MergeResultText, result.ToString()); } /// <summary> /// Test merging a DynamicMessage into a GeneratedMessage. /// As long as they have the same descriptor, this should work, but it is an /// entirely different code path. /// </summary> [TestMethod] public void MergeFromDynamic() { TestAllTypes result = (TestAllTypes) TestAllTypes.CreateBuilder(MergeDest) .MergeFrom(DynamicMessage.CreateBuilder(MergeSource).Build()) .Build(); Assert.AreEqual(MergeResultText, result.ToString()); } /// <summary> /// Test merging two DynamicMessages. /// </summary> [TestMethod] public void DynamicMergeFrom() { DynamicMessage result = (DynamicMessage) DynamicMessage.CreateBuilder(MergeDest) .MergeFrom( (DynamicMessage) DynamicMessage.CreateBuilder(MergeSource).Build()) .Build(); Assert.AreEqual(MergeResultText, result.ToString()); } // ================================================================= // Required-field-related tests. private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance; private static readonly TestRequired TestRequiredInitialized = new TestRequired.Builder { A = 1, B = 2, C = 3 }.Build(); [TestMethod] public void Initialization() { TestRequired.Builder builder = TestRequired.CreateBuilder(); Assert.IsFalse(builder.IsInitialized); builder.A = 1; Assert.IsFalse(builder.IsInitialized); builder.B = 1; Assert.IsFalse(builder.IsInitialized); builder.C = 1; Assert.IsTrue(builder.IsInitialized); } [TestMethod] public void UninitializedBuilderToString() { TestRequired.Builder builder = TestRequired.CreateBuilder().SetA(1); Assert.AreEqual("a: 1\n", builder.ToString()); } [TestMethod] public void RequiredForeign() { TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder(); Assert.IsTrue(builder.IsInitialized); builder.SetOptionalMessage(TestRequiredUninitialized); Assert.IsFalse(builder.IsInitialized); builder.SetOptionalMessage(TestRequiredInitialized); Assert.IsTrue(builder.IsInitialized); builder.AddRepeatedMessage(TestRequiredUninitialized); Assert.IsFalse(builder.IsInitialized); builder.SetRepeatedMessage(0, TestRequiredInitialized); Assert.IsTrue(builder.IsInitialized); } [TestMethod] public void RequiredExtension() { TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); Assert.IsTrue(builder.IsInitialized); builder.SetExtension(TestRequired.Single, TestRequiredUninitialized); Assert.IsFalse(builder.IsInitialized); builder.SetExtension(TestRequired.Single, TestRequiredInitialized); Assert.IsTrue(builder.IsInitialized); builder.AddExtension(TestRequired.Multi, TestRequiredUninitialized); Assert.IsFalse(builder.IsInitialized); builder.SetExtension(TestRequired.Multi, 0, TestRequiredInitialized); Assert.IsTrue(builder.IsInitialized); } [TestMethod] public void RequiredDynamic() { MessageDescriptor descriptor = TestRequired.Descriptor; DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor); Assert.IsFalse(builder.IsInitialized); builder[descriptor.FindDescriptor<FieldDescriptor>("a")] = 1; Assert.IsFalse(builder.IsInitialized); builder[descriptor.FindDescriptor<FieldDescriptor>("b")] = 1; Assert.IsFalse(builder.IsInitialized); builder[descriptor.FindDescriptor<FieldDescriptor>("c")] = 1; Assert.IsTrue(builder.IsInitialized); } [TestMethod] public void RequiredDynamicForeign() { MessageDescriptor descriptor = TestRequiredForeign.Descriptor; DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor); Assert.IsTrue(builder.IsInitialized); builder[descriptor.FindDescriptor<FieldDescriptor>("optional_message")] = TestRequiredUninitialized; Assert.IsFalse(builder.IsInitialized); builder[descriptor.FindDescriptor<FieldDescriptor>("optional_message")] = TestRequiredInitialized; Assert.IsTrue(builder.IsInitialized); builder.AddRepeatedField(descriptor.FindDescriptor<FieldDescriptor>("repeated_message"), TestRequiredUninitialized); Assert.IsFalse(builder.IsInitialized); builder.SetRepeatedField(descriptor.FindDescriptor<FieldDescriptor>("repeated_message"), 0, TestRequiredInitialized); Assert.IsTrue(builder.IsInitialized); } [TestMethod] public void UninitializedException() { try { TestRequired.CreateBuilder().Build(); Assert.Fail("Should have thrown an exception."); } catch (UninitializedMessageException e) { Assert.AreEqual("Message missing required fields: a, b, c", e.Message); } } [TestMethod] public void BuildPartial() { // We're mostly testing that no exception is thrown. TestRequired message = TestRequired.CreateBuilder().BuildPartial(); Assert.IsFalse(message.IsInitialized); } [TestMethod] public void NestedUninitializedException() { try { TestRequiredForeign.CreateBuilder() .SetOptionalMessage(TestRequiredUninitialized) .AddRepeatedMessage(TestRequiredUninitialized) .AddRepeatedMessage(TestRequiredUninitialized) .Build(); Assert.Fail("Should have thrown an exception."); } catch (UninitializedMessageException e) { Assert.AreEqual( "Message missing required fields: " + "optional_message.a, " + "optional_message.b, " + "optional_message.c, " + "repeated_message[0].a, " + "repeated_message[0].b, " + "repeated_message[0].c, " + "repeated_message[1].a, " + "repeated_message[1].b, " + "repeated_message[1].c", e.Message); } } [TestMethod] public void BuildNestedPartial() { // We're mostly testing that no exception is thrown. TestRequiredForeign message = TestRequiredForeign.CreateBuilder() .SetOptionalMessage(TestRequiredUninitialized) .AddRepeatedMessage(TestRequiredUninitialized) .AddRepeatedMessage(TestRequiredUninitialized) .BuildPartial(); Assert.IsFalse(message.IsInitialized); } [TestMethod] public void ParseUnititialized() { try { TestRequired.ParseFrom(ByteString.Empty); Assert.Fail("Should have thrown an exception."); } catch (InvalidProtocolBufferException e) { Assert.AreEqual("Message missing required fields: a, b, c", e.Message); } } [TestMethod] public void ParseNestedUnititialized() { ByteString data = TestRequiredForeign.CreateBuilder() .SetOptionalMessage(TestRequiredUninitialized) .AddRepeatedMessage(TestRequiredUninitialized) .AddRepeatedMessage(TestRequiredUninitialized) .BuildPartial().ToByteString(); try { TestRequiredForeign.ParseFrom(data); Assert.Fail("Should have thrown an exception."); } catch (InvalidProtocolBufferException e) { Assert.AreEqual( "Message missing required fields: " + "optional_message.a, " + "optional_message.b, " + "optional_message.c, " + "repeated_message[0].a, " + "repeated_message[0].b, " + "repeated_message[0].c, " + "repeated_message[1].a, " + "repeated_message[1].b, " + "repeated_message[1].c", e.Message); } } [TestMethod] public void DynamicUninitializedException() { try { DynamicMessage.CreateBuilder(TestRequired.Descriptor).Build(); Assert.Fail("Should have thrown an exception."); } catch (UninitializedMessageException e) { Assert.AreEqual("Message missing required fields: a, b, c", e.Message); } } [TestMethod] public void DynamicBuildPartial() { // We're mostly testing that no exception is thrown. DynamicMessage message = DynamicMessage.CreateBuilder(TestRequired.Descriptor).BuildPartial(); Assert.IsFalse(message.Initialized); } [TestMethod] public void DynamicParseUnititialized() { try { MessageDescriptor descriptor = TestRequired.Descriptor; DynamicMessage.ParseFrom(descriptor, ByteString.Empty); Assert.Fail("Should have thrown an exception."); } catch (InvalidProtocolBufferException e) { Assert.AreEqual("Message missing required fields: a, b, c", e.Message); } } [TestMethod] public void PackedTypesWrittenDirectlyToStream() { TestPackedTypes message = new TestPackedTypes.Builder {PackedInt32List = {0, 1, 2}}.Build(); MemoryStream stream = new MemoryStream(); message.WriteTo(stream); stream.Position = 0; TestPackedTypes readMessage = TestPackedTypes.ParseFrom(stream); Assert.AreEqual(message, readMessage); } } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.1 * * Copyright (c) 2013, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to install, execute and perform the Spine Runtimes * Software (the "Software") solely for internal use. Without the written * permission of Esoteric Software (typically granted by licensing Spine), you * may not (a) modify, translate, adapt or otherwise create derivative works, * improvements of the Software or develop new applications using the Software * or (b) remove, delete, alter or obscure any trademarks or any copyright, * trademark, patent or other intellectual property or proprietary rights * notices on or in the Software, including any copy thereof. Redistributions * in binary or source form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTARE 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. *****************************************************************************/ /***************************************************************************** * Skeleton Utility created by Mitch Thompson * Full irrevocable rights and permissions granted to Esoteric Software *****************************************************************************/ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using Spine; [CustomEditor(typeof(SkeletonUtilityBone)), CanEditMultipleObjects] public class SkeletonUtilityBoneInspector : Editor { SerializedProperty mode, boneName, zPosition, position, rotation, scale, overrideAlpha, parentReference, flip, flipX; //multi selected flags bool containsFollows, containsOverrides, multiObject; //single selected helpers SkeletonUtilityBone utilityBone; SkeletonUtility skeletonUtility; bool canCreateHingeChain = false; void OnEnable () { mode = this.serializedObject.FindProperty("mode"); boneName = this.serializedObject.FindProperty("boneName"); zPosition = this.serializedObject.FindProperty("zPosition"); position = this.serializedObject.FindProperty("position"); rotation = this.serializedObject.FindProperty("rotation"); scale = this.serializedObject.FindProperty("scale"); overrideAlpha = this.serializedObject.FindProperty("overrideAlpha"); parentReference = this.serializedObject.FindProperty("parentReference"); flip = this.serializedObject.FindProperty("flip"); flipX = this.serializedObject.FindProperty("flipX"); EvaluateFlags(); if (utilityBone.valid == false && skeletonUtility != null && skeletonUtility.skeletonRenderer != null) { skeletonUtility.skeletonRenderer.Reset(); } canCreateHingeChain = CanCreateHingeChain(); } void EvaluateFlags () { utilityBone = (SkeletonUtilityBone)target; skeletonUtility = utilityBone.skeletonUtility; if (Selection.objects.Length == 1) { containsFollows = utilityBone.mode == SkeletonUtilityBone.Mode.Follow; containsOverrides = utilityBone.mode == SkeletonUtilityBone.Mode.Override; } else { int boneCount = 0; foreach (Object o in Selection.objects) { if (o is GameObject) { GameObject go = (GameObject)o; SkeletonUtilityBone sub = go.GetComponent<SkeletonUtilityBone>(); if (sub != null) { boneCount++; if (sub.mode == SkeletonUtilityBone.Mode.Follow) containsFollows = true; if (sub.mode == SkeletonUtilityBone.Mode.Override) containsOverrides = true; } } } if (boneCount > 1) multiObject = true; } } public override void OnInspectorGUI () { serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(mode); if (EditorGUI.EndChangeCheck()) { containsOverrides = mode.enumValueIndex == 1; containsFollows = mode.enumValueIndex == 0; } EditorGUI.BeginDisabledGroup(multiObject); { string str = boneName.stringValue; if (str == "") str = "<None>"; if (multiObject) str = "<Multiple>"; GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Bone"); if (GUILayout.Button(str, EditorStyles.popup)) { BoneSelectorContextMenu(str, ((SkeletonUtilityBone)target).skeletonUtility.skeletonRenderer.skeleton.Bones, "<None>", TargetBoneSelected); } GUILayout.EndHorizontal(); } EditorGUI.EndDisabledGroup(); EditorGUILayout.PropertyField(zPosition); EditorGUILayout.PropertyField(position); EditorGUILayout.PropertyField(rotation); EditorGUILayout.PropertyField(scale); EditorGUILayout.PropertyField(flip); EditorGUI.BeginDisabledGroup(containsFollows); { EditorGUILayout.PropertyField(overrideAlpha); EditorGUILayout.PropertyField(parentReference); EditorGUI.BeginDisabledGroup(multiObject || !flip.boolValue); { EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(flipX); if (EditorGUI.EndChangeCheck()) { FlipX(flipX.boolValue); } } EditorGUI.EndDisabledGroup(); } EditorGUI.EndDisabledGroup(); EditorGUILayout.Space(); GUILayout.BeginHorizontal(); { EditorGUI.BeginDisabledGroup(multiObject || !utilityBone.valid || utilityBone.bone == null || utilityBone.bone.Children.Count == 0); { if (GUILayout.Button(new GUIContent("Add Child", SpineEditorUtilities.Icons.bone), GUILayout.Width(150), GUILayout.Height(24))) BoneSelectorContextMenu("", utilityBone.bone.Children, "<Recursively>", SpawnChildBoneSelected); } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(multiObject || !utilityBone.valid || utilityBone.bone == null || containsOverrides); { if (GUILayout.Button(new GUIContent("Add Override", SpineEditorUtilities.Icons.poseBones), GUILayout.Width(150), GUILayout.Height(24))) SpawnOverride(); } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(multiObject || !utilityBone.valid || !canCreateHingeChain); { if (GUILayout.Button(new GUIContent("Create Hinge Chain", SpineEditorUtilities.Icons.hingeChain), GUILayout.Width(150), GUILayout.Height(24))) CreateHingeChain(); } EditorGUI.EndDisabledGroup(); } GUILayout.EndHorizontal(); serializedObject.ApplyModifiedProperties(); } void FlipX (bool state) { utilityBone.FlipX(state); if (Application.isPlaying == false) { skeletonUtility.skeletonAnimation.LateUpdate(); } } void BoneSelectorContextMenu (string current, List<Bone> bones, string topValue, GenericMenu.MenuFunction2 callback) { GenericMenu menu = new GenericMenu(); if (topValue != "") menu.AddItem(new GUIContent(topValue), current == topValue, callback, null); for (int i = 0; i < bones.Count; i++) { menu.AddItem(new GUIContent(bones[i].Data.Name), bones[i].Data.Name == current, callback, bones[i]); } menu.ShowAsContext(); } void TargetBoneSelected (object obj) { if (obj == null) { boneName.stringValue = ""; serializedObject.ApplyModifiedProperties(); } else { Bone bone = (Bone)obj; boneName.stringValue = bone.Data.Name; serializedObject.ApplyModifiedProperties(); utilityBone.Reset(); } } void SpawnChildBoneSelected (object obj) { if (obj == null) { //add recursively foreach (var bone in utilityBone.bone.Children) { GameObject go = skeletonUtility.SpawnBoneRecursively(bone, utilityBone.transform, utilityBone.mode, utilityBone.position, utilityBone.rotation, utilityBone.scale); SkeletonUtilityBone[] newUtilityBones = go.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (SkeletonUtilityBone utilBone in newUtilityBones) SkeletonUtilityInspector.AttachIcon(utilBone); } } else { Bone bone = (Bone)obj; GameObject go = skeletonUtility.SpawnBone(bone, utilityBone.transform, utilityBone.mode, utilityBone.position, utilityBone.rotation, utilityBone.scale); SkeletonUtilityInspector.AttachIcon(go.GetComponent<SkeletonUtilityBone>()); Selection.activeGameObject = go; EditorGUIUtility.PingObject(go); } } void SpawnOverride () { GameObject go = skeletonUtility.SpawnBone(utilityBone.bone, utilityBone.transform.parent, SkeletonUtilityBone.Mode.Override, utilityBone.position, utilityBone.rotation, utilityBone.scale); go.name = go.name + " [Override]"; SkeletonUtilityInspector.AttachIcon(go.GetComponent<SkeletonUtilityBone>()); Selection.activeGameObject = go; EditorGUIUtility.PingObject(go); } bool CanCreateHingeChain () { if (utilityBone == null) return false; if (utilityBone.rigidbody != null) return false; if (utilityBone.bone != null && utilityBone.bone.Children.Count == 0) return false; Rigidbody[] rigidbodies = utilityBone.GetComponentsInChildren<Rigidbody>(); if (rigidbodies.Length > 0) return false; return true; } void CreateHingeChain () { var utilBoneArr = utilityBone.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (var utilBone in utilBoneArr) { AttachRigidbody(utilBone); } utilityBone.rigidbody.isKinematic = true; foreach (var utilBone in utilBoneArr) { if (utilBone == utilityBone) continue; utilBone.mode = SkeletonUtilityBone.Mode.Override; HingeJoint joint = utilBone.gameObject.AddComponent<HingeJoint>(); joint.axis = Vector3.forward; joint.connectedBody = utilBone.transform.parent.rigidbody; joint.useLimits = true; JointLimits limits = new JointLimits(); limits.min = -20; limits.max = 20; joint.limits = limits; utilBone.rigidbody.mass = utilBone.transform.parent.rigidbody.mass * 0.75f; } } void AttachRigidbody (SkeletonUtilityBone utilBone) { if (utilBone.GetComponent<Collider>() == null) { if (utilBone.bone.Data.Length == 0) { SphereCollider sphere = utilBone.gameObject.AddComponent<SphereCollider>(); sphere.radius = 0.1f; } else { float length = utilBone.bone.Data.Length; BoxCollider box = utilBone.gameObject.AddComponent<BoxCollider>(); box.size = new Vector3(length, length / 3, 0.2f); box.center = new Vector3(length / 2, 0, 0); } } utilBone.gameObject.AddComponent<Rigidbody>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Net.Mail; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class HttpRequestHeadersTest { private HttpRequestHeaders headers; public HttpRequestHeadersTest() { headers = new HttpRequestHeaders(); } #region Request headers [Fact] public void Accept_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison() { // Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison. Assert.Throws<FormatException>(() => { headers.Add("AcCePt", "this is invalid"); }); } [Fact] public void Accept_ReadAndWriteProperty_ValueMatchesPriorSetValue() { MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain"); value1.CharSet = "utf-8"; value1.Quality = 0.5; value1.Parameters.Add(new NameValueHeaderValue("custom", "value")); MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("text/plain"); value2.CharSet = "iso-8859-1"; value2.Quality = 0.3868; Assert.Equal(0, headers.Accept.Count); headers.Accept.Add(value1); headers.Accept.Add(value2); Assert.Equal(2, headers.Accept.Count); Assert.Equal(value1, headers.Accept.ElementAt(0)); Assert.Equal(value2, headers.Accept.ElementAt(1)); headers.Accept.Clear(); Assert.Equal(0, headers.Accept.Count); } [Fact] public void Accept_ReadEmptyProperty_EmptyCollection() { HttpRequestMessage request = new HttpRequestMessage(); Assert.Equal(0, request.Headers.Accept.Count); // Copy to another list List<MediaTypeWithQualityHeaderValue> accepts = request.Headers.Accept.ToList(); Assert.Equal(0, accepts.Count); accepts = new List<MediaTypeWithQualityHeaderValue>(request.Headers.Accept); Assert.Equal(0, accepts.Count); } [Fact] public void Accept_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Accept", ",, , ,,text/plain; charset=iso-8859-1; q=1.0,\r\n */xml; charset=utf-8; q=0.5,,,"); MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain"); value1.CharSet = "iso-8859-1"; value1.Quality = 1.0; MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("*/xml"); value2.CharSet = "utf-8"; value2.Quality = 0.5; Assert.Equal(value1, headers.Accept.ElementAt(0)); Assert.Equal(value2, headers.Accept.ElementAt(1)); } [Fact] public void Accept_UseAddMethodWithInvalidValue_InvalidValueRecognized() { // Add a valid media-type with an invalid quality value headers.TryAddWithoutValidation("Accept", "text/plain; q=a"); // invalid quality Assert.NotNull(headers.Accept.First()); Assert.Null(headers.Accept.First().Quality); Assert.Equal("text/plain; q=a", headers.Accept.First().ToString()); headers.Clear(); headers.TryAddWithoutValidation("Accept", "text/plain application/xml"); // no separator Assert.Equal(0, headers.Accept.Count); Assert.Equal(1, headers.GetValues("Accept").Count()); Assert.Equal("text/plain application/xml", headers.GetValues("Accept").First()); } [Fact] public void AcceptCharset_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.AcceptCharset.Count); headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5")); headers.AcceptCharset.Add(new StringWithQualityHeaderValue("unicode-1-1", 0.8)); Assert.Equal(2, headers.AcceptCharset.Count); Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"), headers.AcceptCharset.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("unicode-1-1", 0.8), headers.AcceptCharset.ElementAt(1)); headers.AcceptCharset.Clear(); Assert.Equal(0, headers.AcceptCharset.Count); } [Fact] public void AcceptCharset_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Accept-Charset", ", ,,iso-8859-5 , \r\n utf-8 ; q=0.300 ,,,"); Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"), headers.AcceptCharset.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("utf-8", 0.3), headers.AcceptCharset.ElementAt(1)); } [Fact] public void AcceptCharset_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Accept-Charset", "iso-8859-5 utf-8"); // no separator Assert.Equal(0, headers.AcceptCharset.Count); Assert.Equal(1, headers.GetValues("Accept-Charset").Count()); Assert.Equal("iso-8859-5 utf-8", headers.GetValues("Accept-Charset").First()); headers.Clear(); headers.TryAddWithoutValidation("Accept-Charset", "utf-8; q=1; q=0.3"); Assert.Equal(0, headers.AcceptCharset.Count); Assert.Equal(1, headers.GetValues("Accept-Charset").Count()); Assert.Equal("utf-8; q=1; q=0.3", headers.GetValues("Accept-Charset").First()); } [Fact] public void AcceptCharset_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter() { headers.TryAddWithoutValidation("Accept-Charset", "invalid value"); headers.Add("Accept-Charset", "utf-8"); headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5", 0.5)); foreach (var header in headers.GetHeaderStrings()) { Assert.Equal("Accept-Charset", header.Key); Assert.Equal("utf-8, iso-8859-5; q=0.5, invalid value", header.Value); } } [Fact] public void AcceptEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.AcceptEncoding.Count); headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("compress", 0.9)); headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); Assert.Equal(2, headers.AcceptEncoding.Count); Assert.Equal(new StringWithQualityHeaderValue("compress", 0.9), headers.AcceptEncoding.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("gzip"), headers.AcceptEncoding.ElementAt(1)); headers.AcceptEncoding.Clear(); Assert.Equal(0, headers.AcceptEncoding.Count); } [Fact] public void AcceptEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Accept-Encoding", ", gzip; q=1.0, identity; q=0.5, *;q=0, "); Assert.Equal(new StringWithQualityHeaderValue("gzip", 1), headers.AcceptEncoding.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("identity", 0.5), headers.AcceptEncoding.ElementAt(1)); Assert.Equal(new StringWithQualityHeaderValue("*", 0), headers.AcceptEncoding.ElementAt(2)); headers.AcceptEncoding.Clear(); headers.TryAddWithoutValidation("Accept-Encoding", ""); Assert.Equal(0, headers.AcceptEncoding.Count); Assert.False(headers.Contains("Accept-Encoding")); } [Fact] public void AcceptEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Accept-Encoding", "gzip deflate"); // no separator Assert.Equal(0, headers.AcceptEncoding.Count); Assert.Equal(1, headers.GetValues("Accept-Encoding").Count()); Assert.Equal("gzip deflate", headers.GetValues("Accept-Encoding").First()); headers.Clear(); headers.TryAddWithoutValidation("Accept-Encoding", "compress; q=1; gzip"); Assert.Equal(0, headers.AcceptEncoding.Count); Assert.Equal(1, headers.GetValues("Accept-Encoding").Count()); Assert.Equal("compress; q=1; gzip", headers.GetValues("Accept-Encoding").First()); } [Fact] public void AcceptLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.AcceptLanguage.Count); headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("da")); headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-GB", 0.8)); headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en", 0.7)); Assert.Equal(3, headers.AcceptLanguage.Count); Assert.Equal(new StringWithQualityHeaderValue("da"), headers.AcceptLanguage.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("en-GB", 0.8), headers.AcceptLanguage.ElementAt(1)); Assert.Equal(new StringWithQualityHeaderValue("en", 0.7), headers.AcceptLanguage.ElementAt(2)); headers.AcceptLanguage.Clear(); Assert.Equal(0, headers.AcceptLanguage.Count); } [Fact] public void AcceptLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Accept-Language", " , de-DE;q=0.9,de-AT;q=0.5,*;q=0.010 , "); Assert.Equal(new StringWithQualityHeaderValue("de-DE", 0.9), headers.AcceptLanguage.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("de-AT", 0.5), headers.AcceptLanguage.ElementAt(1)); Assert.Equal(new StringWithQualityHeaderValue("*", 0.01), headers.AcceptLanguage.ElementAt(2)); headers.AcceptLanguage.Clear(); headers.TryAddWithoutValidation("Accept-Language", ""); Assert.Equal(0, headers.AcceptLanguage.Count); Assert.False(headers.Contains("Accept-Language")); } [Fact] public void AcceptLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Accept-Language", "de -DE"); // no separator Assert.Equal(0, headers.AcceptLanguage.Count); Assert.Equal(1, headers.GetValues("Accept-Language").Count()); Assert.Equal("de -DE", headers.GetValues("Accept-Language").First()); headers.Clear(); headers.TryAddWithoutValidation("Accept-Language", "en; q=0.4,["); Assert.Equal(0, headers.AcceptLanguage.Count); Assert.Equal(1, headers.GetValues("Accept-Language").Count()); Assert.Equal("en; q=0.4,[", headers.GetValues("Accept-Language").First()); } [Fact] public void Expect_Add100Continue_Success() { // use non-default casing to make sure we do case-insensitive comparison. headers.Expect.Add(new NameValueWithParametersHeaderValue("100-CONTINUE")); Assert.True(headers.ExpectContinue == true); Assert.Equal(1, headers.Expect.Count); } [Fact] public void Expect_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Expect.Count); Assert.Null(headers.ExpectContinue); headers.Expect.Add(new NameValueWithParametersHeaderValue("custom1")); headers.Expect.Add(new NameValueWithParametersHeaderValue("custom2")); headers.ExpectContinue = true; // Connection collection has 2 values plus '100-Continue' Assert.Equal(3, headers.Expect.Count); Assert.Equal(3, headers.GetValues("Expect").Count()); Assert.True(headers.ExpectContinue == true, "ExpectContinue == true"); Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0)); Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1)); // Remove '100-continue' value from store. But leave other 'Expect' values. headers.ExpectContinue = false; Assert.True(headers.ExpectContinue == false, "ExpectContinue == false"); Assert.Equal(2, headers.Expect.Count); Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0)); Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1)); headers.ExpectContinue = true; headers.Expect.Clear(); Assert.True(headers.ExpectContinue == false, "ExpectContinue should be modified by Expect.Clear()."); Assert.Equal(0, headers.Expect.Count); IEnumerable<string> dummyArray; Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear()."); // Remove '100-continue' value from store. Since there are no other 'Expect' values, remove whole header. headers.ExpectContinue = false; Assert.True(headers.ExpectContinue == false, "ExpectContinue == false"); Assert.Equal(0, headers.Expect.Count); Assert.False(headers.Contains("Expect")); headers.ExpectContinue = null; Assert.Null(headers.ExpectContinue); } [Fact] public void Expect_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Expect", ", , 100-continue, name1 = value1, name2; param2=paramValue2, name3=value3; param3 ,"); // Connection collection has 3 values plus '100-continue' Assert.Equal(4, headers.Expect.Count); Assert.Equal(4, headers.GetValues("Expect").Count()); Assert.True(headers.ExpectContinue == true, "ExpectContinue expected to be true."); Assert.Equal(new NameValueWithParametersHeaderValue("100-continue"), headers.Expect.ElementAt(0)); Assert.Equal(new NameValueWithParametersHeaderValue("name1", "value1"), headers.Expect.ElementAt(1)); NameValueWithParametersHeaderValue expected2 = new NameValueWithParametersHeaderValue("name2"); expected2.Parameters.Add(new NameValueHeaderValue("param2", "paramValue2")); Assert.Equal(expected2, headers.Expect.ElementAt(2)); NameValueWithParametersHeaderValue expected3 = new NameValueWithParametersHeaderValue("name3", "value3"); expected3.Parameters.Add(new NameValueHeaderValue("param3")); Assert.Equal(expected3, headers.Expect.ElementAt(3)); headers.Expect.Clear(); Assert.Null(headers.ExpectContinue); Assert.Equal(0, headers.Expect.Count); IEnumerable<string> dummyArray; Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear()."); } [Fact] public void Expect_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Expect", "100-continue other"); // no separator Assert.Equal(0, headers.Expect.Count); Assert.Equal(1, headers.GetValues("Expect").Count()); Assert.Equal("100-continue other", headers.GetValues("Expect").First()); } [Fact] public void Host_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Host); headers.Host = "host"; Assert.Equal("host", headers.Host); headers.Host = null; Assert.Null(headers.Host); Assert.False(headers.Contains("Host"), "Header store should not contain a header 'Host' after setting it to null."); Assert.Throws<FormatException>(() => { headers.Host = "invalid host"; }); } [Fact] public void Host_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Host", "host:80"); Assert.Equal("host:80", headers.Host); } [Fact] public void IfMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.IfMatch.Count); headers.IfMatch.Add(new EntityTagHeaderValue("\"custom1\"")); headers.IfMatch.Add(new EntityTagHeaderValue("\"custom2\"", true)); Assert.Equal(2, headers.IfMatch.Count); Assert.Equal(2, headers.GetValues("If-Match").Count()); Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfMatch.ElementAt(0)); Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfMatch.ElementAt(1)); headers.IfMatch.Clear(); Assert.Equal(0, headers.IfMatch.Count); Assert.False(headers.Contains("If-Match"), "Header store should not contain 'If-Match'"); } [Fact] public void IfMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-Match", ", , W/\"tag1\", \"tag2\", W/\"tag3\" ,"); Assert.Equal(3, headers.IfMatch.Count); Assert.Equal(3, headers.GetValues("If-Match").Count()); Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfMatch.ElementAt(0)); Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfMatch.ElementAt(1)); Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfMatch.ElementAt(2)); headers.IfMatch.Clear(); headers.Add("If-Match", "*"); Assert.Equal(1, headers.IfMatch.Count); Assert.Same(EntityTagHeaderValue.Any, headers.IfMatch.ElementAt(0)); } [Fact] public void IfMatch_UseAddMethodWithInvalidInput_PropertyNotUpdated() { headers.TryAddWithoutValidation("If-Match", "W/\"tag1\" \"tag2\""); // no separator Assert.Equal(0, headers.IfMatch.Count); Assert.Equal(1, headers.GetValues("If-Match").Count()); } [Fact] public void IfNoneMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.IfNoneMatch.Count); headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom1\"")); headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom2\"", true)); Assert.Equal(2, headers.IfNoneMatch.Count); Assert.Equal(2, headers.GetValues("If-None-Match").Count()); Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfNoneMatch.ElementAt(0)); Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfNoneMatch.ElementAt(1)); headers.IfNoneMatch.Clear(); Assert.Equal(0, headers.IfNoneMatch.Count); Assert.False(headers.Contains("If-None-Match"), "Header store should not contain 'If-None-Match'"); } [Fact] public void IfNoneMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-None-Match", "W/\"tag1\", \"tag2\", W/\"tag3\""); Assert.Equal(3, headers.IfNoneMatch.Count); Assert.Equal(3, headers.GetValues("If-None-Match").Count()); Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfNoneMatch.ElementAt(0)); Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfNoneMatch.ElementAt(1)); Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfNoneMatch.ElementAt(2)); headers.IfNoneMatch.Clear(); headers.Add("If-None-Match", "*"); Assert.Equal(1, headers.IfNoneMatch.Count); Assert.Same(EntityTagHeaderValue.Any, headers.IfNoneMatch.ElementAt(0)); } [Fact] public void TE_ReadAndWriteProperty_ValueMatchesPriorSetValue() { TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom"); value1.Quality = 0.5; value1.Parameters.Add(new NameValueHeaderValue("name", "value")); TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom"); value2.Quality = 0.3868; Assert.Equal(0, headers.TE.Count); headers.TE.Add(value1); headers.TE.Add(value2); Assert.Equal(2, headers.TE.Count); Assert.Equal(value1, headers.TE.ElementAt(0)); Assert.Equal(value2, headers.TE.ElementAt(1)); headers.TE.Clear(); Assert.Equal(0, headers.TE.Count); } [Fact] public void TE_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("TE", ",custom1; param1=value1; q=1.0,,\r\n custom2; param2=value2; q=0.5 ,"); TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom1"); value1.Parameters.Add(new NameValueHeaderValue("param1", "value1")); value1.Quality = 1.0; TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom2"); value2.Parameters.Add(new NameValueHeaderValue("param2", "value2")); value2.Quality = 0.5; Assert.Equal(value1, headers.TE.ElementAt(0)); Assert.Equal(value2, headers.TE.ElementAt(1)); headers.Clear(); headers.TryAddWithoutValidation("TE", ""); Assert.False(headers.Contains("TE"), "'TE' header should not be added if it just has empty values."); } [Fact] public void Range_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Range); RangeHeaderValue value = new RangeHeaderValue(1, 2); headers.Range = value; Assert.Equal(value, headers.Range); headers.Range = null; Assert.Null(headers.Range); } [Fact] public void Range_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Range", "custom= , ,1-2, -4 , "); RangeHeaderValue value = new RangeHeaderValue(); value.Unit = "custom"; value.Ranges.Add(new RangeItemHeaderValue(1, 2)); value.Ranges.Add(new RangeItemHeaderValue(null, 4)); Assert.Equal(value, headers.Range); } [Fact] public void Authorization_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Authorization); headers.Authorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="), headers.Authorization); headers.Authorization = null; Assert.Null(headers.Authorization); Assert.False(headers.Contains("Authorization"), "Header store should not contain a header 'Authorization' after setting it to null."); } [Fact] public void Authorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Authorization", "NTLM blob"); Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.Authorization); } [Fact] public void ProxyAuthorization_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.ProxyAuthorization); headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="), headers.ProxyAuthorization); headers.ProxyAuthorization = null; Assert.Null(headers.ProxyAuthorization); Assert.False(headers.Contains("ProxyAuthorization"), "Header store should not contain a header 'ProxyAuthorization' after setting it to null."); } [Fact] public void ProxyAuthorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Proxy-Authorization", "NTLM blob"); Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.ProxyAuthorization); } [Fact] public void UserAgent_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.UserAgent.Count); headers.UserAgent.Add(new ProductInfoHeaderValue("(custom1)")); headers.UserAgent.Add(new ProductInfoHeaderValue("custom2", "1.1")); Assert.Equal(2, headers.UserAgent.Count); Assert.Equal(2, headers.GetValues("User-Agent").Count()); Assert.Equal(new ProductInfoHeaderValue("(custom1)"), headers.UserAgent.ElementAt(0)); Assert.Equal(new ProductInfoHeaderValue("custom2", "1.1"), headers.UserAgent.ElementAt(1)); headers.UserAgent.Clear(); Assert.Equal(0, headers.UserAgent.Count); Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear()."); headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)")); headers.UserAgent.Remove(new ProductInfoHeaderValue("(comment)")); Assert.Equal(0, headers.UserAgent.Count); Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after removing last value."); } [Fact] public void UserAgent_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("User-Agent", "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.6.30 Version/10.63"); Assert.Equal(4, headers.UserAgent.Count); Assert.Equal(4, headers.GetValues("User-Agent").Count()); Assert.Equal(new ProductInfoHeaderValue("Opera", "9.80"), headers.UserAgent.ElementAt(0)); Assert.Equal(new ProductInfoHeaderValue("(Windows NT 6.1; U; en)"), headers.UserAgent.ElementAt(1)); Assert.Equal(new ProductInfoHeaderValue("Presto", "2.6.30"), headers.UserAgent.ElementAt(2)); Assert.Equal(new ProductInfoHeaderValue("Version", "10.63"), headers.UserAgent.ElementAt(3)); headers.UserAgent.Clear(); Assert.Equal(0, headers.UserAgent.Count); Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear()."); } [Fact] public void UserAgent_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A"); Assert.Null(headers.GetParsedValues("User-Agent")); Assert.Equal(1, headers.GetValues("User-Agent").Count()); Assert.Equal("custom\u4F1A", headers.GetValues("User-Agent").First()); headers.Clear(); // Note that "User-Agent" uses whitespaces as separators, so the following is an invalid value headers.TryAddWithoutValidation("User-Agent", "custom1, custom2"); Assert.Null(headers.GetParsedValues("User-Agent")); Assert.Equal(1, headers.GetValues("User-Agent").Count()); Assert.Equal("custom1, custom2", headers.GetValues("User-Agent").First()); headers.Clear(); headers.TryAddWithoutValidation("User-Agent", "custom1, "); Assert.Null(headers.GetParsedValues("User-Agent")); Assert.Equal(1, headers.GetValues("User-Agent").Count()); Assert.Equal("custom1, ", headers.GetValues("User-Agent").First()); headers.Clear(); headers.TryAddWithoutValidation("User-Agent", ",custom1"); Assert.Null(headers.GetParsedValues("User-Agent")); Assert.Equal(1, headers.GetValues("User-Agent").Count()); Assert.Equal(",custom1", headers.GetValues("User-Agent").First()); } [Fact] public void UserAgent_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter() { headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A"); headers.Add("User-Agent", "custom2/1.1"); headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)")); foreach (var header in headers.GetHeaderStrings()) { Assert.Equal("User-Agent", header.Key); Assert.Equal("custom2/1.1 (comment) custom\u4F1A", header.Value); } } [Fact] public void IfRange_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.IfRange); headers.IfRange = new RangeConditionHeaderValue("\"x\""); Assert.Equal(1, headers.GetValues("If-Range").Count()); Assert.Equal(new RangeConditionHeaderValue("\"x\""), headers.IfRange); headers.IfRange = null; Assert.Null(headers.IfRange); Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear()."); } [Fact] public void IfRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-Range", " W/\"tag\" "); Assert.Equal(new RangeConditionHeaderValue(new EntityTagHeaderValue("\"tag\"", true)), headers.IfRange); Assert.Equal(1, headers.GetValues("If-Range").Count()); headers.IfRange = null; Assert.Null(headers.IfRange); Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear()."); } [Fact] public void IfRange_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("If-Range", "\"tag\"\u4F1A"); Assert.Null(headers.GetParsedValues("If-Range")); Assert.Equal(1, headers.GetValues("If-Range").Count()); Assert.Equal("\"tag\"\u4F1A", headers.GetValues("If-Range").First()); headers.Clear(); headers.TryAddWithoutValidation("If-Range", " \"tag\", "); Assert.Null(headers.GetParsedValues("If-Range")); Assert.Equal(1, headers.GetValues("If-Range").Count()); Assert.Equal(" \"tag\", ", headers.GetValues("If-Range").First()); } [Fact] public void From_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.From); headers.From = "[email protected]"; Assert.Equal("[email protected]", headers.From); headers.From = null; Assert.Null(headers.From); Assert.False(headers.Contains("From"), "Header store should not contain a header 'From' after setting it to null."); Assert.Throws<FormatException>(() => { headers.From = " "; }); Assert.Throws<FormatException>(() => { headers.From = "invalid email address"; }); } [Fact] public void From_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("From", " \"My Name\" [email protected] "); Assert.Equal("\"My Name\" [email protected] ", headers.From); // The following encoded string represents the character sequence "\u4F1A\u5458\u670D\u52A1". headers.Clear(); headers.TryAddWithoutValidation("From", "=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <[email protected]>"); Assert.Equal("=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <[email protected]>", headers.From); } [Fact] public void From_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("From", " [email protected] ,"); Assert.Null(headers.GetParsedValues("From")); Assert.Equal(1, headers.GetValues("From").Count()); Assert.Equal(" [email protected] ,", headers.GetValues("From").First()); headers.Clear(); headers.TryAddWithoutValidation("From", "info@"); Assert.Null(headers.GetParsedValues("From")); Assert.Equal(1, headers.GetValues("From").Count()); Assert.Equal("info@", headers.GetValues("From").First()); } [Fact] public void IfModifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.IfModifiedSince); DateTimeOffset expected = DateTimeOffset.Now; headers.IfModifiedSince = expected; Assert.Equal(expected, headers.IfModifiedSince); headers.IfModifiedSince = null; Assert.Null(headers.IfModifiedSince); Assert.False(headers.Contains("If-Modified-Since"), "Header store should not contain a header 'IfModifiedSince' after setting it to null."); } [Fact] public void IfModifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince); headers.Clear(); headers.TryAddWithoutValidation("If-Modified-Since", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince); } [Fact] public void IfModifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(headers.GetParsedValues("If-Modified-Since")); Assert.Equal(1, headers.GetValues("If-Modified-Since").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Modified-Since").First()); headers.Clear(); headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov "); Assert.Null(headers.GetParsedValues("If-Modified-Since")); Assert.Equal(1, headers.GetValues("If-Modified-Since").Count()); Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Modified-Since").First()); } [Fact] public void IfUnmodifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.IfUnmodifiedSince); DateTimeOffset expected = DateTimeOffset.Now; headers.IfUnmodifiedSince = expected; Assert.Equal(expected, headers.IfUnmodifiedSince); headers.IfUnmodifiedSince = null; Assert.Null(headers.IfUnmodifiedSince); Assert.False(headers.Contains("If-Unmodified-Since"), "Header store should not contain a header 'IfUnmodifiedSince' after setting it to null."); } [Fact] public void IfUnmodifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince); headers.Clear(); headers.TryAddWithoutValidation("If-Unmodified-Since", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince); } [Fact] public void IfUnmodifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(headers.GetParsedValues("If-Unmodified-Since")); Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Unmodified-Since").First()); headers.Clear(); headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov "); Assert.Null(headers.GetParsedValues("If-Unmodified-Since")); Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count()); Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Unmodified-Since").First()); } [Fact] public void Referrer_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Referrer); Uri expected = new Uri("http://example.com/path/"); headers.Referrer = expected; Assert.Equal(expected, headers.Referrer); headers.Referrer = null; Assert.Null(headers.Referrer); Assert.False(headers.Contains("Referer"), "Header store should not contain a header 'Referrer' after setting it to null."); } [Fact] public void Referrer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Referer", " http://www.example.com/path/?q=v "); Assert.Equal(new Uri("http://www.example.com/path/?q=v"), headers.Referrer); headers.Clear(); headers.TryAddWithoutValidation("Referer", "/relative/uri/"); Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), headers.Referrer); } [Fact] public void Referrer_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Referer", " http://example.com http://other"); Assert.Null(headers.GetParsedValues("Referer")); Assert.Equal(1, headers.GetValues("Referer").Count()); Assert.Equal(" http://example.com http://other", headers.GetValues("Referer").First()); headers.Clear(); headers.TryAddWithoutValidation("Referer", "http://host /other"); Assert.Null(headers.GetParsedValues("Referer")); Assert.Equal(1, headers.GetValues("Referer").Count()); Assert.Equal("http://host /other", headers.GetValues("Referer").First()); } [Fact] public void MaxForwards_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.MaxForwards); headers.MaxForwards = 15; Assert.Equal(15, headers.MaxForwards); headers.MaxForwards = null; Assert.Null(headers.MaxForwards); Assert.False(headers.Contains("Max-Forwards"), "Header store should not contain a header 'MaxForwards' after setting it to null."); // Make sure the header gets serialized correctly headers.MaxForwards = 12345; Assert.Equal("12345", headers.GetValues("Max-Forwards").First()); } [Fact] public void MaxForwards_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Max-Forwards", " 00123 "); Assert.Equal(123, headers.MaxForwards); headers.Clear(); headers.TryAddWithoutValidation("Max-Forwards", "0"); Assert.Equal(0, headers.MaxForwards); } [Fact] public void MaxForwards_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Max-Forwards", "15,"); Assert.Null(headers.GetParsedValues("Max-Forwards")); Assert.Equal(1, headers.GetValues("Max-Forwards").Count()); Assert.Equal("15,", headers.GetValues("Max-Forwards").First()); headers.Clear(); headers.TryAddWithoutValidation("Max-Forwards", "1.0"); Assert.Null(headers.GetParsedValues("Max-Forwards")); Assert.Equal(1, headers.GetValues("Max-Forwards").Count()); Assert.Equal("1.0", headers.GetValues("Max-Forwards").First()); } [Fact] public void AddHeaders_SpecialHeaderValuesOnSourceNotOnDestination_Copied() { // Positive HttpRequestHeaders source = new HttpRequestHeaders(); source.ExpectContinue = true; source.TransferEncodingChunked = true; source.ConnectionClose = true; HttpRequestHeaders destination = new HttpRequestHeaders(); Assert.Null(destination.ExpectContinue); Assert.Null(destination.TransferEncodingChunked); Assert.Null(destination.ConnectionClose); destination.AddHeaders(source); Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.True(destination.ExpectContinue.Value); Assert.True(destination.TransferEncodingChunked.Value); Assert.True(destination.ConnectionClose.Value); // Negitive source = new HttpRequestHeaders(); source.ExpectContinue = false; source.TransferEncodingChunked = false; source.ConnectionClose = false; destination = new HttpRequestHeaders(); Assert.Null(destination.ExpectContinue); Assert.Null(destination.TransferEncodingChunked); Assert.Null(destination.ConnectionClose); destination.AddHeaders(source); Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.False(destination.ExpectContinue.Value); Assert.False(destination.TransferEncodingChunked.Value); Assert.False(destination.ConnectionClose.Value); } [Fact] public void AddHeaders_SpecialHeaderValuesOnDestinationNotOnSource_NotCopied() { // Positive HttpRequestHeaders destination = new HttpRequestHeaders(); destination.ExpectContinue = true; destination.TransferEncodingChunked = true; destination.ConnectionClose = true; Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.True(destination.ExpectContinue.Value); Assert.True(destination.TransferEncodingChunked.Value); Assert.True(destination.ConnectionClose.Value); HttpRequestHeaders source = new HttpRequestHeaders(); Assert.Null(source.ExpectContinue); Assert.Null(source.TransferEncodingChunked); Assert.Null(source.ConnectionClose); destination.AddHeaders(source); Assert.Null(source.ExpectContinue); Assert.Null(source.TransferEncodingChunked); Assert.Null(source.ConnectionClose); Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.True(destination.ExpectContinue.Value); Assert.True(destination.TransferEncodingChunked.Value); Assert.True(destination.ConnectionClose.Value); // Negitive destination = new HttpRequestHeaders(); destination.ExpectContinue = false; destination.TransferEncodingChunked = false; destination.ConnectionClose = false; Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.False(destination.ExpectContinue.Value); Assert.False(destination.TransferEncodingChunked.Value); Assert.False(destination.ConnectionClose.Value); source = new HttpRequestHeaders(); Assert.Null(source.ExpectContinue); Assert.Null(source.TransferEncodingChunked); Assert.Null(source.ConnectionClose); destination.AddHeaders(source); Assert.Null(source.ExpectContinue); Assert.Null(source.TransferEncodingChunked); Assert.Null(source.ConnectionClose); Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.False(destination.ExpectContinue.Value); Assert.False(destination.TransferEncodingChunked.Value); Assert.False(destination.ConnectionClose.Value); } #endregion #region General headers [Fact] public void Connection_AddClose_Success() { headers.Connection.Add("CLOSE"); // use non-default casing to make sure we do case-insensitive comparison. Assert.True(headers.ConnectionClose == true); Assert.Equal(1, headers.Connection.Count); } [Fact] public void Connection_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Connection.Count); Assert.Null(headers.ConnectionClose); headers.Connection.Add("custom1"); headers.Connection.Add("custom2"); headers.ConnectionClose = true; // Connection collection has 2 values plus 'close' Assert.Equal(3, headers.Connection.Count); Assert.Equal(3, headers.GetValues("Connection").Count()); Assert.True(headers.ConnectionClose == true, "ConnectionClose"); Assert.Equal("custom1", headers.Connection.ElementAt(0)); Assert.Equal("custom2", headers.Connection.ElementAt(1)); // Remove 'close' value from store. But leave other 'Connection' values. headers.ConnectionClose = false; Assert.True(headers.ConnectionClose == false, "ConnectionClose == false"); Assert.Equal(2, headers.Connection.Count); Assert.Equal("custom1", headers.Connection.ElementAt(0)); Assert.Equal("custom2", headers.Connection.ElementAt(1)); headers.ConnectionClose = true; headers.Connection.Clear(); Assert.True(headers.ConnectionClose == false, "ConnectionClose should be modified by Connection.Clear()."); Assert.Equal(0, headers.Connection.Count); IEnumerable<string> dummyArray; Assert.False(headers.TryGetValues("Connection", out dummyArray), "Connection header count after Connection.Clear()."); // Remove 'close' value from store. Since there are no other 'Connection' values, remove whole header. headers.ConnectionClose = false; Assert.True(headers.ConnectionClose == false, "ConnectionClose == false"); Assert.Equal(0, headers.Connection.Count); Assert.False(headers.Contains("Connection")); headers.ConnectionClose = null; Assert.Null(headers.ConnectionClose); } [Fact] public void Connection_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Connection", "custom1, close, custom2, custom3"); // Connection collection has 3 values plus 'close' Assert.Equal(4, headers.Connection.Count); Assert.Equal(4, headers.GetValues("Connection").Count()); Assert.True(headers.ConnectionClose == true); Assert.Equal("custom1", headers.Connection.ElementAt(0)); Assert.Equal("close", headers.Connection.ElementAt(1)); Assert.Equal("custom2", headers.Connection.ElementAt(2)); Assert.Equal("custom3", headers.Connection.ElementAt(3)); headers.Connection.Clear(); Assert.Null(headers.ConnectionClose); Assert.Equal(0, headers.Connection.Count); IEnumerable<string> dummyArray; Assert.False(headers.TryGetValues("Connection", out dummyArray), "Connection header count after Connection.Clear()."); } [Fact] public void Connection_AddInvalidValue_Throw() { Assert.Throws<FormatException>(() => { headers.Connection.Add("this is invalid"); }); } [Fact] public void TransferEncoding_AddChunked_Success() { // use non-default casing to make sure we do case-insensitive comparison. headers.TransferEncoding.Add(new TransferCodingHeaderValue("CHUNKED")); Assert.True(headers.TransferEncodingChunked == true); Assert.Equal(1, headers.TransferEncoding.Count); } [Fact] public void TransferEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.TransferEncoding.Count); Assert.Null(headers.TransferEncodingChunked); headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom1")); headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom2")); headers.TransferEncodingChunked = true; // Connection collection has 2 values plus 'chunked' Assert.Equal(3, headers.TransferEncoding.Count); Assert.Equal(3, headers.GetValues("Transfer-Encoding").Count()); Assert.Equal(true, headers.TransferEncodingChunked); Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0)); Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1)); // Remove 'chunked' value from store. But leave other 'Transfer-Encoding' values. Note that according to // the RFC this is not valid, since 'chunked' must always be present. However this check is done // in the transport handler since the user can add invalid header values anyways. headers.TransferEncodingChunked = false; Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false"); Assert.Equal(2, headers.TransferEncoding.Count); Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0)); Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1)); headers.TransferEncodingChunked = true; headers.TransferEncoding.Clear(); Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked should be modified by TransferEncoding.Clear()."); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.Contains("Transfer-Encoding")); // Remove 'chunked' value from store. Since there are no other 'Transfer-Encoding' values, remove whole // header. headers.TransferEncodingChunked = false; Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false"); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.Contains("Transfer-Encoding")); headers.TransferEncodingChunked = null; Assert.Null(headers.TransferEncodingChunked); } [Fact] public void TransferEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Transfer-Encoding", " , custom1, , custom2, custom3, chunked ,"); // Connection collection has 3 values plus 'chunked' Assert.Equal(4, headers.TransferEncoding.Count); Assert.Equal(4, headers.GetValues("Transfer-Encoding").Count()); Assert.True(headers.TransferEncodingChunked == true, "TransferEncodingChunked expected to be true."); Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0)); Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1)); Assert.Equal(new TransferCodingHeaderValue("custom3"), headers.TransferEncoding.ElementAt(2)); headers.TransferEncoding.Clear(); Assert.Null(headers.TransferEncodingChunked); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.Contains("Transfer-Encoding"), "Transfer-Encoding header after TransferEncoding.Clear()."); } [Fact] public void TransferEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Transfer-Encoding", "custom\u4F1A"); Assert.Null(headers.GetParsedValues("Transfer-Encoding")); Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count()); Assert.Equal("custom\u4F1A", headers.GetValues("Transfer-Encoding").First()); headers.Clear(); headers.TryAddWithoutValidation("Transfer-Encoding", "custom1 custom2"); Assert.Null(headers.GetParsedValues("Transfer-Encoding")); Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count()); Assert.Equal("custom1 custom2", headers.GetValues("Transfer-Encoding").First()); headers.Clear(); headers.TryAddWithoutValidation("Transfer-Encoding", ""); Assert.False(headers.Contains("Transfer-Encoding"), "'Transfer-Encoding' header should not be added if it just has empty values."); } [Fact] public void Upgrade_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Upgrade.Count); headers.Upgrade.Add(new ProductHeaderValue("custom1")); headers.Upgrade.Add(new ProductHeaderValue("custom2", "1.1")); Assert.Equal(2, headers.Upgrade.Count); Assert.Equal(2, headers.GetValues("Upgrade").Count()); Assert.Equal(new ProductHeaderValue("custom1"), headers.Upgrade.ElementAt(0)); Assert.Equal(new ProductHeaderValue("custom2", "1.1"), headers.Upgrade.ElementAt(1)); headers.Upgrade.Clear(); Assert.Equal(0, headers.Upgrade.Count); Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear()."); } [Fact] public void Upgrade_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Upgrade", " , custom1 / 1.0, , custom2, custom3/2.0,"); Assert.Equal(3, headers.Upgrade.Count); Assert.Equal(3, headers.GetValues("Upgrade").Count()); Assert.Equal(new ProductHeaderValue("custom1", "1.0"), headers.Upgrade.ElementAt(0)); Assert.Equal(new ProductHeaderValue("custom2"), headers.Upgrade.ElementAt(1)); Assert.Equal(new ProductHeaderValue("custom3", "2.0"), headers.Upgrade.ElementAt(2)); headers.Upgrade.Clear(); Assert.Equal(0, headers.Upgrade.Count); Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear()."); } [Fact] public void Upgrade_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Upgrade", "custom\u4F1A"); Assert.Null(headers.GetParsedValues("Upgrade")); Assert.Equal(1, headers.GetValues("Upgrade").Count()); Assert.Equal("custom\u4F1A", headers.GetValues("Upgrade").First()); headers.Clear(); headers.TryAddWithoutValidation("Upgrade", "custom1 custom2"); Assert.Null(headers.GetParsedValues("Upgrade")); Assert.Equal(1, headers.GetValues("Upgrade").Count()); Assert.Equal("custom1 custom2", headers.GetValues("Upgrade").First()); } [Fact] public void Date_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Date); DateTimeOffset expected = DateTimeOffset.Now; headers.Date = expected; Assert.Equal(expected, headers.Date); headers.Date = null; Assert.Null(headers.Date); Assert.False(headers.Contains("Date"), "Header store should not contain a header 'Date' after setting it to null."); // Make sure the header gets serialized correctly headers.Date = (new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero)); Assert.Equal("Sun, 06 Nov 1994 08:49:37 GMT", headers.GetValues("Date").First()); } [Fact] public void Date_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date); headers.Clear(); headers.TryAddWithoutValidation("Date", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date); } [Fact] public void Date_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(headers.GetParsedValues("Date")); Assert.Equal(1, headers.GetValues("Date").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("Date").First()); headers.Clear(); headers.TryAddWithoutValidation("Date", " Sun, 06 Nov "); Assert.Null(headers.GetParsedValues("Date")); Assert.Equal(1, headers.GetValues("Date").Count()); Assert.Equal(" Sun, 06 Nov ", headers.GetValues("Date").First()); } [Fact] public void Via_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Via.Count); headers.Via.Add(new ViaHeaderValue("x11", "host")); headers.Via.Add(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)")); Assert.Equal(2, headers.Via.Count); Assert.Equal(new ViaHeaderValue("x11", "host"), headers.Via.ElementAt(0)); Assert.Equal(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)"), headers.Via.ElementAt(1)); headers.Via.Clear(); Assert.Equal(0, headers.Via.Count); } [Fact] public void Via_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Via", ", 1.1 host, WS/1.0 [::1],X/11 192.168.0.1 (c(comment)) "); Assert.Equal(new ViaHeaderValue("1.1", "host"), headers.Via.ElementAt(0)); Assert.Equal(new ViaHeaderValue("1.0", "[::1]", "WS"), headers.Via.ElementAt(1)); Assert.Equal(new ViaHeaderValue("11", "192.168.0.1", "X", "(c(comment))"), headers.Via.ElementAt(2)); headers.Via.Clear(); headers.TryAddWithoutValidation("Via", ""); Assert.Equal(0, headers.Via.Count); Assert.False(headers.Contains("Via")); } [Fact] public void Via_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Via", "1.1 host1 1.1 host2"); // no separator Assert.Equal(0, headers.Via.Count); Assert.Equal(1, headers.GetValues("Via").Count()); Assert.Equal("1.1 host1 1.1 host2", headers.GetValues("Via").First()); headers.Clear(); headers.TryAddWithoutValidation("Via", "X/11 host/1"); Assert.Equal(0, headers.Via.Count); Assert.Equal(1, headers.GetValues("Via").Count()); Assert.Equal("X/11 host/1", headers.GetValues("Via").First()); } [Fact] public void Warning_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Warning.Count); headers.Warning.Add(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\"")); headers.Warning.Add(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\"")); Assert.Equal(2, headers.Warning.Count); Assert.Equal(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\""), headers.Warning.ElementAt(0)); Assert.Equal(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\""), headers.Warning.ElementAt(1)); headers.Warning.Clear(); Assert.Equal(0, headers.Warning.Count); } [Fact] public void Warning_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Warning", "112 example.com \"Disconnected operation\", 111 example.org \"Revalidation failed\""); Assert.Equal(new WarningHeaderValue(112, "example.com", "\"Disconnected operation\""), headers.Warning.ElementAt(0)); Assert.Equal(new WarningHeaderValue(111, "example.org", "\"Revalidation failed\""), headers.Warning.ElementAt(1)); headers.Warning.Clear(); headers.TryAddWithoutValidation("Warning", ""); Assert.Equal(0, headers.Warning.Count); Assert.False(headers.Contains("Warning")); } [Fact] public void Warning_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Warning", "123 host1 \"\" 456 host2 \"\""); // no separator Assert.Equal(0, headers.Warning.Count); Assert.Equal(1, headers.GetValues("Warning").Count()); Assert.Equal("123 host1 \"\" 456 host2 \"\"", headers.GetValues("Warning").First()); headers.Clear(); headers.TryAddWithoutValidation("Warning", "123 host1\"text\""); Assert.Equal(0, headers.Warning.Count); Assert.Equal(1, headers.GetValues("Warning").Count()); Assert.Equal("123 host1\"text\"", headers.GetValues("Warning").First()); } [Fact] public void CacheControl_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.CacheControl); CacheControlHeaderValue value = new CacheControlHeaderValue(); value.NoCache = true; value.NoCacheHeaders.Add("token1"); value.NoCacheHeaders.Add("token2"); value.MustRevalidate = true; value.SharedMaxAge = new TimeSpan(1, 2, 3); headers.CacheControl = value; Assert.Equal(value, headers.CacheControl); headers.CacheControl = null; Assert.Null(headers.CacheControl); Assert.False(headers.Contains("Cache-Control"), "Header store should not contain a header 'Cache-Control' after setting it to null."); } [Fact] public void CacheControl_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Cache-Control", "no-cache=\"token1, token2\", must-revalidate, max-age=3"); headers.Add("Cache-Control", ""); headers.Add("Cache-Control", "public, s-maxage=15"); headers.TryAddWithoutValidation("Cache-Control", ""); CacheControlHeaderValue value = new CacheControlHeaderValue(); value.NoCache = true; value.NoCacheHeaders.Add("token1"); value.NoCacheHeaders.Add("token2"); value.MustRevalidate = true; value.MaxAge = new TimeSpan(0, 0, 3); value.Public = true; value.SharedMaxAge = new TimeSpan(0, 0, 15); Assert.Equal(value, headers.CacheControl); } [Fact] public void Trailer_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Trailer.Count); headers.Trailer.Add("custom1"); headers.Trailer.Add("custom2"); Assert.Equal(2, headers.Trailer.Count); Assert.Equal(2, headers.GetValues("Trailer").Count()); Assert.Equal("custom1", headers.Trailer.ElementAt(0)); Assert.Equal("custom2", headers.Trailer.ElementAt(1)); headers.Trailer.Clear(); Assert.Equal(0, headers.Trailer.Count); Assert.False(headers.Contains("Trailer"), "There should be no Trailer header after calling Clear()."); } [Fact] public void Trailer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Trailer", ",custom1, custom2, custom3,"); Assert.Equal(3, headers.Trailer.Count); Assert.Equal(3, headers.GetValues("Trailer").Count()); Assert.Equal("custom1", headers.Trailer.ElementAt(0)); Assert.Equal("custom2", headers.Trailer.ElementAt(1)); Assert.Equal("custom3", headers.Trailer.ElementAt(2)); headers.Trailer.Clear(); Assert.Equal(0, headers.Trailer.Count); Assert.False(headers.Contains("Trailer"), "There should be no Trailer header after calling Clear()."); } [Fact] public void Trailer_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Trailer", "custom1 custom2"); // no separator Assert.Equal(0, headers.Trailer.Count); Assert.Equal(1, headers.GetValues("Trailer").Count()); Assert.Equal("custom1 custom2", headers.GetValues("Trailer").First()); } [Fact] public void Pragma_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Pragma.Count); headers.Pragma.Add(new NameValueHeaderValue("custom1", "value1")); headers.Pragma.Add(new NameValueHeaderValue("custom2")); Assert.Equal(2, headers.Pragma.Count); Assert.Equal(2, headers.GetValues("Pragma").Count()); Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0)); Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1)); headers.Pragma.Clear(); Assert.Equal(0, headers.Pragma.Count); Assert.False(headers.Contains("Pragma"), "There should be no Pragma header after calling Clear()."); } [Fact] public void Pragma_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Pragma", ",custom1=value1, custom2, custom3=value3,"); Assert.Equal(3, headers.Pragma.Count); Assert.Equal(3, headers.GetValues("Pragma").Count()); Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0)); Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1)); Assert.Equal(new NameValueHeaderValue("custom3", "value3"), headers.Pragma.ElementAt(2)); headers.Pragma.Clear(); Assert.Equal(0, headers.Pragma.Count); Assert.False(headers.Contains("Pragma"), "There should be no Pragma header after calling Clear()."); } [Fact] public void Pragma_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Pragma", "custom1, custom2="); Assert.Equal(0, headers.Pragma.Count()); Assert.Equal(1, headers.GetValues("Pragma").Count()); Assert.Equal("custom1, custom2=", headers.GetValues("Pragma").First()); } #endregion [Fact] public void ToString_SeveralRequestHeaders_Success() { HttpRequestMessage request = new HttpRequestMessage(); string expected = string.Empty; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/xml")); expected += HttpKnownHeaderNames.Accept + ": application/xml, */xml\r\n"; request.Headers.Authorization = new AuthenticationHeaderValue("Basic"); expected += HttpKnownHeaderNames.Authorization + ": Basic\r\n"; request.Headers.ExpectContinue = true; expected += HttpKnownHeaderNames.Expect + ": 100-continue\r\n"; request.Headers.TransferEncodingChunked = true; expected += HttpKnownHeaderNames.TransferEncoding + ": chunked\r\n"; Assert.Equal(expected, request.Headers.ToString()); } [Fact] public void CustomHeaders_ResponseHeadersAsCustomHeaders_Success() { // Header names reserved for response headers are permitted as custom request headers. headers.Add("Accept-Ranges", "v"); headers.TryAddWithoutValidation("age", "v"); headers.Add("ETag", "v"); headers.Add("Location", "v"); headers.Add("Proxy-Authenticate", "v"); headers.Add("Retry-After", "v"); headers.Add("Server", "v"); headers.Add("Vary", "v"); headers.Add("WWW-Authenticate", "v"); } [Fact] public void InvalidHeaders_AddContentHeaders_Throw() { // Try adding content headers. Use different casing to make sure case-insensitive comparison // is used. Assert.Throws<InvalidOperationException>(() => { headers.Add("Allow", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Encoding", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Language", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("content-length", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Location", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-MD5", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Range", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("CONTENT-TYPE", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Expires", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Last-Modified", "v"); }); } } }
#if !SILVERLIGHT && !PocketPC using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Text; using System.Threading; using System.Globalization; namespace Newtonsoft.Json.Utilities { internal class DynamicWrapperBase { internal protected object UnderlyingObject; } internal static class DynamicWrapper { private static readonly object _lock = new object(); private static readonly WrapperDictionary _wrapperDictionary = new WrapperDictionary(); private static ModuleBuilder _moduleBuilder; private static ModuleBuilder ModuleBuilder { get { Init(); return _moduleBuilder; } } private static void Init() { if (_moduleBuilder == null) { lock (_lock) { if (_moduleBuilder == null) { AssemblyName assemblyName = new AssemblyName("Newtonsoft.Json.Dynamic"); assemblyName.KeyPair = new StrongNameKeyPair(GetStrongKey()); AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); _moduleBuilder = assembly.DefineDynamicModule("Newtonsoft.Json.DynamicModule", false); } } } } private static byte[] GetStrongKey() { string name ="Newtonsoft.Json.Dynamic.snk"; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) { if (stream == null) throw new MissingManifestResourceException("Should have " + name + " as an embedded resource."); int length = (int)stream.Length; byte[] buffer = new byte[length]; stream.Read(buffer, 0, length); return buffer; } } public static Type GetWrapper(Type interfaceType, Type realObjectType) { Type wrapperType = _wrapperDictionary.GetType(interfaceType, realObjectType); if (wrapperType == null) { lock (_lock) { wrapperType = _wrapperDictionary.GetType(interfaceType, realObjectType); if (wrapperType == null) { wrapperType = GenerateWrapperType(interfaceType, realObjectType); _wrapperDictionary.SetType(interfaceType, realObjectType, wrapperType); } } } return wrapperType; } public static object GetUnderlyingObject(object wrapper) { DynamicWrapperBase wrapperBase = wrapper as DynamicWrapperBase; if (wrapperBase == null) throw new ArgumentException("Object is not a wrapper.", "wrapper"); return wrapperBase.UnderlyingObject; } private static Type GenerateWrapperType(Type interfaceType, Type underlyingType) { TypeBuilder wrapperBuilder = ModuleBuilder.DefineType( "{0}_{1}_Wrapper".FormatWith(CultureInfo.InvariantCulture, interfaceType.Name, underlyingType.Name), TypeAttributes.NotPublic | TypeAttributes.Sealed, typeof(DynamicWrapperBase), new[] { interfaceType }); WrapperMethodBuilder wrapperMethod = new WrapperMethodBuilder(underlyingType, wrapperBuilder); foreach (MethodInfo method in interfaceType.AllMethods()) { wrapperMethod.Generate(method); } return wrapperBuilder.CreateType(); } public static T CreateWrapper<T>(object realObject) where T : class { var dynamicType = GetWrapper(typeof(T), realObject.GetType()); var dynamicWrapper = (DynamicWrapperBase)Activator.CreateInstance(dynamicType); dynamicWrapper.UnderlyingObject = realObject; return dynamicWrapper as T; } } internal class WrapperMethodBuilder { private readonly Type _realObjectType; private readonly TypeBuilder _wrapperBuilder; public WrapperMethodBuilder(Type realObjectType, TypeBuilder proxyBuilder) { _realObjectType = realObjectType; _wrapperBuilder = proxyBuilder; } public void Generate(MethodInfo newMethod) { if (newMethod.IsGenericMethod) newMethod = newMethod.GetGenericMethodDefinition(); FieldInfo srcField = typeof(DynamicWrapperBase).GetField("UnderlyingObject", BindingFlags.Instance | BindingFlags.NonPublic); var parameters = newMethod.GetParameters(); var parameterTypes = parameters.Select(parameter => parameter.ParameterType).ToArray(); MethodBuilder methodBuilder = _wrapperBuilder.DefineMethod( newMethod.Name, MethodAttributes.Public | MethodAttributes.Virtual, newMethod.ReturnType, parameterTypes); if (newMethod.IsGenericMethod) { methodBuilder.DefineGenericParameters( newMethod.GetGenericArguments().Select(arg => arg.Name).ToArray()); } ILGenerator ilGenerator = methodBuilder.GetILGenerator(); LoadUnderlyingObject(ilGenerator, srcField); PushParameters(parameters, ilGenerator); ExecuteMethod(newMethod, parameterTypes, ilGenerator); Return(ilGenerator); } private static void Return(ILGenerator ilGenerator) { ilGenerator.Emit(OpCodes.Ret); } private void ExecuteMethod(MethodBase newMethod, Type[] parameterTypes, ILGenerator ilGenerator) { MethodInfo srcMethod = GetMethod(newMethod, parameterTypes); if (srcMethod == null) throw new MissingMethodException("Unable to find method " + newMethod.Name + " on " + _realObjectType.FullName); ilGenerator.Emit(OpCodes.Call, srcMethod); } private MethodInfo GetMethod(MethodBase realMethod, Type[] parameterTypes) { if (realMethod.IsGenericMethod) return _realObjectType.GetGenericMethod(realMethod.Name, parameterTypes); return _realObjectType.GetMethod(realMethod.Name, parameterTypes); } private static void PushParameters(ICollection<ParameterInfo> parameters, ILGenerator ilGenerator) { for (int i = 1; i < parameters.Count + 1; i++) ilGenerator.Emit(OpCodes.Ldarg, i); } private static void LoadUnderlyingObject(ILGenerator ilGenerator, FieldInfo srcField) { ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, srcField); } } internal class WrapperDictionary { private readonly Dictionary<string, Type> _wrapperTypes = new Dictionary<string, Type>(); private static string GenerateKey(Type interfaceType, Type realObjectType) { return interfaceType.Name + "_" + realObjectType.Name; } public Type GetType(Type interfaceType, Type realObjectType) { string key = GenerateKey(interfaceType, realObjectType); if (_wrapperTypes.ContainsKey(key)) return _wrapperTypes[key]; return null; } public void SetType(Type interfaceType, Type realObjectType, Type wrapperType) { string key = GenerateKey(interfaceType, realObjectType); if (_wrapperTypes.ContainsKey(key)) _wrapperTypes[key] = wrapperType; else _wrapperTypes.Add(key, wrapperType); } } internal static class TypeExtensions { public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes) { var methods = type.GetMethods().Where(method => method.Name == name); foreach (var method in methods) { if (method.HasParameters(parameterTypes)) return method; } return null; } public static bool HasParameters(this MethodInfo method, params Type[] parameterTypes) { var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); if (methodParameters.Length != parameterTypes.Length) return false; for (int i = 0; i < methodParameters.Length; i++) if (methodParameters[i].ToString() != parameterTypes[i].ToString()) return false; return true; } public static IEnumerable<Type> AllInterfaces(this Type target) { foreach (var IF in target.GetInterfaces()) { yield return IF; foreach (var childIF in IF.AllInterfaces()) { yield return childIF; } } } public static IEnumerable<MethodInfo> AllMethods(this Type target) { var allTypes = target.AllInterfaces().ToList(); allTypes.Add(target); return from type in allTypes from method in type.GetMethods() select method; } } } #endif
using System; using System.IO; using System.Threading; using System.Diagnostics; using System.Net; using System.Text; using DarkMultiPlayerCommon; using UDPMeshLib; namespace DarkMultiPlayerServer { public class Server { public static bool serverRunning; public static bool serverStarting; public static bool serverRestarting; public static string universeDirectory; public static string configDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config"); public static Stopwatch serverClock; public static HttpListener httpListener; public static UdpMeshServer meshServer; private static Thread meshServerThread; private static long ctrlCTime; public static int playerCount = 0; public static string players = ""; public static long lastPlayerActivity; public static object universeSizeLock = new object(); public static string modFile; private static int day; public static void Main() { #if !DEBUG try { #endif //Start the server clock serverClock = new Stopwatch(); serverClock.Start(); Settings.Reset(); //Set the last player activity time to server start lastPlayerActivity = serverClock.ElapsedMilliseconds; //Periodic garbage collection long lastGarbageCollect = 0; //Periodic screenshot check long lastScreenshotExpiredCheck = 0; //Periodic log check long lastLogExpiredCheck = 0; //Periodic day check long lastDayCheck = 0; //Set universe directory universeDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Universe"); if (!Directory.Exists(configDirectory)) { Directory.CreateDirectory(configDirectory); } string oldSettingsFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DMPServerSettings.txt"); string newSettingsFile = Path.Combine(configDirectory, "Settings.txt"); string oldGameplayFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DMPGameplaySettings.txt"); string newGameplayFile = Path.Combine(configDirectory, "GameplaySettings.txt"); // Run the conversion BackwardsCompatibility.ConvertSettings(oldSettingsFile, newSettingsFile); if (File.Exists(oldGameplayFile)) { if (!File.Exists(newGameplayFile)) { File.Move(oldGameplayFile, newGameplayFile); } File.Delete(oldGameplayFile); } string oldModFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DMPModControl.txt"); modFile = Path.Combine(configDirectory, "mod-control.txt"); // Move mod control file to Config/mod-control.txt if (File.Exists(oldModFile)) { if (!File.Exists(modFile)) { File.Move(oldModFile, modFile); } File.Delete(modFile); } // Move DMPPlayerBans to Config/banned-players.txt string oldBanlistFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DMPPlayerBans.txt"); string newBanlistFile = Path.Combine(configDirectory, "banned-players.txt"); if (File.Exists(oldBanlistFile)) { if (!File.Exists(newBanlistFile)) { File.Move(oldBanlistFile, newBanlistFile); } File.Delete(oldBanlistFile); } // Move DMPIPBans to Config/banned-ips.txt oldBanlistFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DMPIPBans.txt"); newBanlistFile = Path.Combine(configDirectory, "banned-ips.txt"); if (File.Exists(oldBanlistFile)) { if (!File.Exists(newBanlistFile)) { File.Move(oldBanlistFile, newBanlistFile); } File.Delete(oldBanlistFile); } // Move DMPKeyBans to Config/banned-keys.txt oldBanlistFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DMPKeyBans.txt"); newBanlistFile = Path.Combine(configDirectory, "banned-keys.txt"); if (File.Exists(oldBanlistFile)) { if (!File.Exists(newBanlistFile)) { File.Move(oldBanlistFile, newBanlistFile); } File.Delete(oldBanlistFile); } // Move DMPAdmins to Config/admins.txt string oldAdminsFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DMPAdmins.txt"); string newAdminsFile = Path.Combine(configDirectory, "admins.txt"); if (File.Exists(oldAdminsFile)) { if (!File.Exists(newAdminsFile)) { File.Move(oldAdminsFile, newAdminsFile); } File.Delete(oldAdminsFile); } //Register the server commands CommandHandler.RegisterCommand("exit", Server.ShutDown, "Shuts down the server"); CommandHandler.RegisterCommand("quit", Server.ShutDown, "Shuts down the server"); CommandHandler.RegisterCommand("shutdown", Server.ShutDown, "Shuts down the server"); CommandHandler.RegisterCommand("restart", Server.Restart, "Restarts the server"); CommandHandler.RegisterCommand("kick", KickCommand.KickPlayer, "Kicks a player from the server"); CommandHandler.RegisterCommand("ban", BanSystem.fetch.BanPlayer, "Bans a player from the server"); CommandHandler.RegisterCommand("banip", BanSystem.fetch.BanIP, "Bans an IP Address from the server"); CommandHandler.RegisterCommand("bankey", BanSystem.fetch.BanPublicKey, "Bans a Guid from the server"); CommandHandler.RegisterCommand("pm", PMCommand.HandleCommand, "Sends a message to a player"); CommandHandler.RegisterCommand("admin", AdminCommand.HandleCommand, "Sets a player as admin/removes admin from the player"); CommandHandler.RegisterCommand("whitelist", WhitelistCommand.HandleCommand, "Change the server whitelist"); //Register the ctrl+c event Console.CancelKeyPress += new ConsoleCancelEventHandler(CatchExit); serverStarting = true; //Fix kerbals from 0.23.5 to 0.24 (Now indexed by string, thanks Squad! BackwardsCompatibility.FixKerbals(); //Remove player tokens BackwardsCompatibility.RemoveOldPlayerTokens(); //Add new stock parts BackwardsCompatibility.UpdateModcontrolPartList(); if (System.Net.Sockets.Socket.OSSupportsIPv6) { Settings.settingsStore.address = "::"; } DarkLog.Debug("Loading settings..."); Settings.Load(); if (Settings.settingsStore.gameDifficulty == GameDifficulty.CUSTOM) { GameplaySettings.Reset(); GameplaySettings.Load(); } //Test compression if (Settings.settingsStore.compressionEnabled) { Compression.compressionEnabled = true; } //Set day for log change day = DateTime.Now.Day; //Load plugins DMPPluginHandler.LoadPlugins(); Console.Title = "DMPServer " + Common.PROGRAM_VERSION + ", protocol " + Common.PROTOCOL_VERSION; while (serverStarting || serverRestarting) { if (serverRestarting) { DarkLog.Debug("Reloading settings..."); Settings.Reset(); Settings.Load(); if (Settings.settingsStore.gameDifficulty == GameDifficulty.CUSTOM) { DarkLog.Debug("Reloading gameplay settings..."); GameplaySettings.Reset(); GameplaySettings.Load(); } } serverRestarting = false; DarkLog.Normal("Starting DMPServer " + Common.PROGRAM_VERSION + ", protocol " + Common.PROTOCOL_VERSION); if (Settings.settingsStore.gameDifficulty == GameDifficulty.CUSTOM) { //Generate the config file by accessing the object. DarkLog.Debug("Loading gameplay settings..."); GameplaySettings.Load(); } if (Settings.settingsStore.modpackMode == ModpackMode.GAMEDATA) { DarkLog.Normal("Loading modpack data"); ModpackSystem.fetch.LoadAuto(); CommandHandler.RegisterCommand("reloadmods", ModpackSystem.fetch.HandleReloadCommand, "Reload Game"); DarkLog.Normal("Loaded data!"); } //Load universe DarkLog.Normal("Loading universe... "); CheckUniverse(); DarkLog.Normal("Starting " + Settings.settingsStore.warpMode + " server on port " + Settings.settingsStore.port + "... "); serverRunning = true; Thread commandThread = new Thread(new ThreadStart(CommandHandler.ThreadMain)); Thread clientThread = new Thread(new ThreadStart(ClientHandler.ThreadMain)); commandThread.Start(); clientThread.Start(); while (serverStarting) { Thread.Sleep(500); } StartMeshServer(); StartHTTPServer(); DarkLog.Normal("Ready!"); DMPPluginHandler.FireOnServerStart(); while (serverRunning) { //Run a garbage collection every 30 seconds. if ((serverClock.ElapsedMilliseconds - lastGarbageCollect) > 30000) { lastGarbageCollect = serverClock.ElapsedMilliseconds; GC.Collect(); } //Run the screenshot expire function every 10 minutes if ((serverClock.ElapsedMilliseconds - lastScreenshotExpiredCheck) > 600000) { lastScreenshotExpiredCheck = serverClock.ElapsedMilliseconds; ScreenshotExpire.ExpireScreenshots(); } //Run the log expire function every 10 minutes if ((serverClock.ElapsedMilliseconds - lastLogExpiredCheck) > 600000) { lastLogExpiredCheck = serverClock.ElapsedMilliseconds; LogExpire.ExpireLogs(); } // Check if the day has changed, every minute if ((serverClock.ElapsedMilliseconds - lastDayCheck) > 60000) { lastDayCheck = serverClock.ElapsedMilliseconds; if (day != DateTime.Now.Day) { DarkLog.LogFilename = Path.Combine(DarkLog.LogFolder, "dmpserver " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".log"); DarkLog.WriteToLog("Continued from logfile " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".log"); day = DateTime.Now.Day; } } Thread.Sleep(500); } DMPPluginHandler.FireOnServerStop(); commandThread.Abort(); clientThread.Join(); } DarkLog.Normal("Goodbye!"); Environment.Exit(0); #if !DEBUG } catch (Exception e) { DarkLog.Fatal("Error in main server thread, Exception: " + e); throw; } #endif } // Check universe folder size public static long GetUniverseSize() { lock (universeSizeLock) { long directorySize = 0; string[] kerbals = Directory.GetFiles(Path.Combine(universeDirectory, "Kerbals"), "*.*"); string[] vessels = Directory.GetFiles(Path.Combine(universeDirectory, "Vessels"), "*.*"); foreach (string kerbal in kerbals) { FileInfo kInfo = new FileInfo(kerbal); directorySize += kInfo.Length; } foreach (string vessel in vessels) { FileInfo vInfo = new FileInfo(vessel); directorySize += vInfo.Length; } return directorySize; } } //Get last disconnect time public static long GetLastPlayerActivity() { if (playerCount > 0) { return 0; } return (serverClock.ElapsedMilliseconds - lastPlayerActivity) / 1000; } //Create universe directories private static void CheckUniverse() { if (!File.Exists(modFile)) { GenerateNewModFile(); } if (!Directory.Exists(universeDirectory)) { Directory.CreateDirectory(universeDirectory); } if (!Directory.Exists(Path.Combine(universeDirectory, "Crafts"))) { Directory.CreateDirectory(Path.Combine(universeDirectory, "Crafts")); } if (!Directory.Exists(Path.Combine(universeDirectory, "Flags"))) { Directory.CreateDirectory(Path.Combine(universeDirectory, "Flags")); } if (!Directory.Exists(Path.Combine(universeDirectory, "Players"))) { Directory.CreateDirectory(Path.Combine(universeDirectory, "Players")); } if (!Settings.settingsStore.sendPlayerToLatestSubspace) { if (!Directory.Exists(Path.Combine(universeDirectory, "OfflinePlayerTimes"))) { Directory.CreateDirectory(Path.Combine(universeDirectory, "OfflinePlayerTimes")); } } if (!Directory.Exists(Path.Combine(universeDirectory, "Kerbals"))) { Directory.CreateDirectory(Path.Combine(universeDirectory, "Kerbals")); } if (!Directory.Exists(Path.Combine(universeDirectory, "Vessels"))) { Directory.CreateDirectory(Path.Combine(universeDirectory, "Vessels")); } if (!Directory.Exists(Path.Combine(universeDirectory, "Scenarios"))) { Directory.CreateDirectory(Path.Combine(universeDirectory, "Scenarios")); } if (!Directory.Exists(Path.Combine(universeDirectory, "Scenarios", "Initial"))) { Directory.CreateDirectory(Path.Combine(universeDirectory, "Scenarios", "Initial")); } } //Get mod file SHA public static string GetModControlSHA() { return Common.CalculateSHA256Hash(modFile); } public static void GenerateNewModFile() { if (File.Exists(modFile)) { File.Move(modFile, modFile + ".bak"); } string modFileData = Common.GenerateModFileStringData(new string[0], new string[0], false, new string[0], Common.GetStockParts().ToArray()); using (StreamWriter sw = new StreamWriter(modFile)) { sw.Write(modFileData); } } //Shutdown public static void ShutDown(string commandArgs) { if (commandArgs != "") { DarkLog.Normal("Shutting down - " + commandArgs); Messages.ConnectionEnd.SendConnectionEndToAll("Server is shutting down - " + commandArgs); } else { DarkLog.Normal("Shutting down"); Messages.ConnectionEnd.SendConnectionEndToAll("Server is shutting down"); } serverStarting = false; serverRunning = false; StopHTTPServer(); StopMeshServer(); } //Restart public static void Restart(string reason) { if (reason != "") { DarkLog.Normal("Restarting - " + reason); Messages.ConnectionEnd.SendConnectionEndToAll("Server is restarting - " + reason); } else { DarkLog.Normal("Restarting"); Messages.ConnectionEnd.SendConnectionEndToAll("Server is restarting"); } serverRestarting = true; serverStarting = false; serverRunning = false; ForceStopHTTPServer(); StopMeshServer(); } //Gracefully shut down private static void CatchExit(object sender, ConsoleCancelEventArgs args) { //If control+c not pressed within 5 seconds, catch it and shutdown gracefully. if ((DateTime.UtcNow.Ticks - ctrlCTime) > 50000000) { ctrlCTime = DateTime.UtcNow.Ticks; args.Cancel = true; ShutDown("Caught Ctrl+C"); } else { DarkLog.Debug("Terminating!"); } } private static void StartMeshServer() { //Only enable mesh server when we can bind on all ports if (Settings.settingsStore.address == "0.0.0.0" || Settings.settingsStore.address == "::") { DarkLog.Debug("Starting mesh server"); meshServer = new UdpMeshServer(Settings.settingsStore.port, DarkLog.Debug); meshServerThread = meshServer.Start(); } else { DarkLog.Normal("Not starting mesh server because we are bound on a specific address"); } } private static void StopMeshServer() { DarkLog.Debug("Stopping mesh server"); meshServer.Shutdown(); meshServerThread = null; } private static void StartHTTPServer() { string OS = Environment.OSVersion.Platform.ToString(); if (Settings.settingsStore.httpPort > 0) { DarkLog.Normal("Starting HTTP server..."); httpListener = new HttpListener(); try { if (Settings.settingsStore.address != "0.0.0.0" && Settings.settingsStore.address != "::") { string listenAddress = Settings.settingsStore.address; if (listenAddress.Contains(":")) { //Sorry DarkLog.Error("Error: The server status port does not support specific IPv6 addresses. Sorry."); //listenAddress = "[" + listenAddress + "]"; return; } httpListener.Prefixes.Add("http://" + listenAddress + ":" + Settings.settingsStore.httpPort + '/'); } else { httpListener.Prefixes.Add("http://*:" + Settings.settingsStore.httpPort + '/'); } httpListener.Start(); httpListener.BeginGetContext(asyncHTTPCallback, httpListener); } catch (HttpListenerException e) { if (OS == "Win32NT" || OS == "Win32S" || OS == "Win32Windows" || OS == "WinCE") // if OS is Windows { if (e.ErrorCode == 5) // Access Denied { DarkLog.Debug("HTTP Server: access denied."); DarkLog.Debug("Prompting user to switch to administrator mode."); ProcessStartInfo startInfo = new ProcessStartInfo("DMPServer.exe") { Verb = "runas" }; Process.Start(startInfo); Environment.Exit(0); } } else { DarkLog.Fatal("Error while starting HTTP server.\n" + e); } throw; } } } private static void StopHTTPServer() { if (Settings.settingsStore.httpPort > 0) { DarkLog.Normal("Stopping HTTP server..."); httpListener.Stop(); } } private static void ForceStopHTTPServer() { if (Settings.settingsStore.httpPort > 0) { DarkLog.Normal("Force stopping HTTP server..."); if (httpListener != null) { try { httpListener.Abort(); } catch (Exception e) { DarkLog.Fatal("Error trying to shutdown HTTP server: " + e); throw; } } } } private static void asyncHTTPCallback(IAsyncResult result) { try { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); string responseText = ""; bool handled = false; if (context.Request.Url.PathAndQuery.StartsWith("/modcontrol", StringComparison.Ordinal)) { if (!File.Exists(modFile)) { GenerateNewModFile(); } responseText = File.ReadAllText(modFile); handled = true; } if (!handled) { responseText = new ServerInfo(Settings.settingsStore).GetJSON(); } byte[] buffer = Encoding.UTF8.GetBytes(responseText); context.Response.ContentLength64 = buffer.LongLength; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Close(); listener.BeginGetContext(asyncHTTPCallback, listener); } catch (Exception e) { //Ignore the EngGetContext throw while shutting down the HTTP server. if (serverRunning) { DarkLog.Error("Exception while listening to HTTP server!, Exception:\n" + e); Thread.Sleep(1000); httpListener.BeginGetContext(asyncHTTPCallback, httpListener); } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.StackPanel.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class StackPanel : Panel, System.Windows.Controls.Primitives.IScrollInfo #if NETFRAMEWORK_4_5 , IStackMeasure #endif { #region Methods and constructors protected override System.Windows.Size ArrangeOverride(System.Windows.Size arrangeSize) { return default(System.Windows.Size); } public void LineDown() { } public void LineLeft() { } public void LineRight() { } public void LineUp() { } public System.Windows.Rect MakeVisible(System.Windows.Media.Visual visual, System.Windows.Rect rectangle) { return default(System.Windows.Rect); } protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint) { return default(System.Windows.Size); } public void MouseWheelDown() { } public void MouseWheelLeft() { } public void MouseWheelRight() { } public void MouseWheelUp() { } public void PageDown() { } public void PageLeft() { } public void PageRight() { } public void PageUp() { } public void SetHorizontalOffset(double offset) { } public void SetVerticalOffset(double offset) { } public StackPanel() { } #endregion #region Properties and indexers public bool CanHorizontallyScroll { get { return default(bool); } set { } } public bool CanVerticallyScroll { get { return default(bool); } set { } } public double ExtentHeight { get { return default(double); } } public double ExtentWidth { get { return default(double); } } internal protected override bool HasLogicalOrientation { get { return default(bool); } } public double HorizontalOffset { get { return default(double); } } internal protected override System.Windows.Controls.Orientation LogicalOrientation { get { return default(System.Windows.Controls.Orientation); } } public Orientation Orientation { get { return default(Orientation); } set { } } public ScrollViewer ScrollOwner { get { return default(ScrollViewer); } set { } } public double VerticalOffset { get { return default(double); } } public double ViewportHeight { get { return default(double); } } public double ViewportWidth { get { return default(double); } } #endregion #region Fields public readonly static System.Windows.DependencyProperty OrientationProperty; #endregion } }
using System; using System.Linq; using System.Collections; using System.Xml; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Core.Strings; using umbraco.DataLayer; using System.Text.RegularExpressions; using System.IO; using System.Collections.Generic; using umbraco.cms.businesslogic.cache; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.web; namespace umbraco.cms.businesslogic.template { /// <summary> /// Summary description for Template. /// </summary> [Obsolete("Obsolete, Use IFileService and ITemplate to work with templates instead")] public class Template : CMSNode { #region Private members private readonly ViewHelper _viewHelper = new ViewHelper(new PhysicalFileSystem(SystemDirectories.MvcViews)); private readonly MasterPageHelper _masterPageHelper = new MasterPageHelper(new PhysicalFileSystem(SystemDirectories.Masterpages)); internal ITemplate TemplateEntity; private int? _mastertemplate; #endregion #region Static members public static readonly string UmbracoMasterTemplate = SystemDirectories.Umbraco + "/masterpages/default.master"; private static Hashtable _templateAliases = new Hashtable(); #endregion [Obsolete("Use TemplateFilePath instead")] public string MasterPageFile { get { return TemplateFilePath; } } /// <summary> /// Returns the file path for the current template /// </summary> public string TemplateFilePath { get { switch (ApplicationContext.Current.Services.FileService.DetermineTemplateRenderingEngine(TemplateEntity)) { case RenderingEngine.Mvc: return _viewHelper.GetPhysicalFilePath(TemplateEntity); case RenderingEngine.WebForms: return _masterPageHelper.GetPhysicalFilePath(TemplateEntity); default: throw new ArgumentOutOfRangeException(); } } } [Obsolete("This is not used at all, do not use this")] public static Hashtable TemplateAliases { get { return _templateAliases; } set { _templateAliases = value; } } #region Constructors internal Template(ITemplate template) : base(template) { TemplateEntity = template; } public Template(int id) : base(id) { } public Template(Guid id) : base(id) { } #endregion /// <summary> /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility /// </summary> public override void Save() { SaveEventArgs e = new SaveEventArgs(); FireBeforeSave(e); if (!e.Cancel) { ApplicationContext.Current.Services.FileService.SaveTemplate(TemplateEntity); //base.Save(); FireAfterSave(e); } } public string GetRawText() { return TemplateEntity.Name; //return base.Text; } //TODO: This is the name of the template, which can apparenlty be localized using the umbraco dictionary, so we need to cater for this but that // shoud really be done as part of mapping logic for models that are being consumed in the UI, not at the business logic layer. public override string Text { get { var tempText = TemplateEntity.Name; //string tempText = base.Text; if (!tempText.StartsWith("#")) return tempText; else { language.Language lang = language.Language.GetByCultureCode(System.Threading.Thread.CurrentThread.CurrentCulture.Name); if (lang != null) { if (Dictionary.DictionaryItem.hasKey(tempText.Substring(1, tempText.Length - 1))) { Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(tempText.Substring(1, tempText.Length - 1)); if (di != null) return di.Value(lang.id); } } return "[" + tempText + "]"; } } set { FlushCache(); TemplateEntity.Name = value; } } [Obsolete("This is not used whatsoever")] public string OutputContentType { get; set; } protected override void setupNode() { TemplateEntity = ApplicationContext.Current.Services.FileService.GetTemplate(Id); if (TemplateEntity == null) { throw new ArgumentException(string.Format("No node exists with id '{0}'", Id)); } } public new string Path { get { return TemplateEntity.Path; } set { TemplateEntity.Path = value; } } public string Alias { get { return TemplateEntity.Alias; } set { TemplateEntity.Alias = value; } } public bool HasMasterTemplate { get { return (_mastertemplate > 0); } } public override bool HasChildren { get { return TemplateEntity.IsMasterTemplate; } set { //Do nothing! } } public int MasterTemplate { get { if (_mastertemplate.HasValue == false) { var master = ApplicationContext.Current.Services.FileService.GetTemplate(TemplateEntity.MasterTemplateAlias); if (master != null) { _mastertemplate = master.Id; } else { _mastertemplate = -1; } } return _mastertemplate.Value; } set { //set to null if it's zero if (value == 0) { TemplateEntity.SetMasterTemplate(null); } else { var found = ApplicationContext.Current.Services.FileService.GetTemplate(value); if (found != null) { TemplateEntity.SetMasterTemplate(found); _mastertemplate = found.Id; } } } } public string Design { get { return TemplateEntity.Content; } set { TemplateEntity.Content = value; } } public XmlNode ToXml(XmlDocument doc) { var serializer = new EntityXmlSerializer(); var serialized = serializer.Serialize(TemplateEntity); return serialized.GetXmlNode(doc); } /// <summary> /// Removes any references to this templates from child templates, documenttypes and documents /// </summary> public void RemoveAllReferences() { if (HasChildren) { foreach (var t in GetAllAsList().FindAll(t => t.MasterTemplate == Id)) { t.MasterTemplate = 0; t.Save(); } } RemoveFromDocumentTypes(); // remove from documents Document.RemoveTemplateFromDocument(this.Id); //save it Save(); } public void RemoveFromDocumentTypes() { foreach (DocumentType dt in DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id))) { dt.RemoveTemplate(this.Id); dt.Save(); } } [Obsolete("This method should have never existed here")] public IEnumerable<DocumentType> GetDocumentTypes() { return DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)); } public static Template MakeNew(string Name, User u, Template master) { return MakeNew(Name, u, master, null); } private static Template MakeNew(string name, User u, string design) { return MakeNew(name, u, null, design); } public static Template MakeNew(string name, User u) { return MakeNew(name, u, design: null); } private static Template MakeNew(string name, User u, Template master, string design) { var foundMaster = master == null ? null : ApplicationContext.Current.Services.FileService.GetTemplate(master.Id); var template = ApplicationContext.Current.Services.FileService.CreateTemplateWithIdentity(name, design, foundMaster, u.Id); var legacyTemplate = new Template(template); var e = new NewEventArgs(); legacyTemplate.OnNew(e); return legacyTemplate; } public static Template GetByAlias(string Alias) { return GetByAlias(Alias, false); } [Obsolete("this overload is the same as the other one, the useCache has no affect")] public static Template GetByAlias(string Alias, bool useCache) { var found = ApplicationContext.Current.Services.FileService.GetTemplate(Alias); return found == null ? null : new Template(found); } [Obsolete("Obsolete, please use GetAllAsList() method instead", true)] public static Template[] getAll() { return GetAllAsList().ToArray(); } public static List<Template> GetAllAsList() { return ApplicationContext.Current.Services.FileService.GetTemplates().Select(x => new Template(x)).ToList(); } public static int GetTemplateIdFromAlias(string alias) { var found = ApplicationContext.Current.Services.FileService.GetTemplate(alias); return found == null ? -1 : found.Id; } public override void delete() { // don't allow template deletion if it has child templates if (this.HasChildren) { var ex = new InvalidOperationException("Can't delete a master template. Remove any bindings from child templates first."); LogHelper.Error<Template>("Can't delete a master template. Remove any bindings from child templates first.", ex); throw ex; } DeleteEventArgs e = new DeleteEventArgs(); FireBeforeDelete(e); if (!e.Cancel) { //remove refs from documents using (var sqlHelper = Application.SqlHelper) sqlHelper.ExecuteNonQuery("UPDATE cmsDocument SET templateId = NULL WHERE templateId = " + this.Id); ApplicationContext.Current.Services.FileService.DeleteTemplate(TemplateEntity.Alias); FireAfterDelete(e); } } [Obsolete("This method, doesnt actually do anything, as the file is created when the design is set", false)] public void _SaveAsMasterPage() { } public string GetMasterContentElement(int masterTemplateId) { if (masterTemplateId != 0) { string masterAlias = new Template(masterTemplateId).Alias.Replace(" ", ""); return String.Format("<asp:Content ContentPlaceHolderID=\"{1}ContentPlaceHolder\" runat=\"server\">", Alias.Replace(" ", ""), masterAlias); } else return String.Format("<asp:Content ContentPlaceHolderID=\"ContentPlaceHolderDefault\" runat=\"server\">", Alias.Replace(" ", "")); } public List<string> contentPlaceholderIds() { return MasterPageHelper.GetContentPlaceholderIds(TemplateEntity).ToList(); } public string ConvertToMasterPageSyntax(string templateDesign) { string masterPageContent = GetMasterContentElement(MasterTemplate) + Environment.NewLine; masterPageContent += templateDesign; // Parse the design for getitems masterPageContent = EnsureMasterPageSyntax(masterPageContent); // append ending asp:content element masterPageContent += Environment.NewLine + "</asp:Content>" + Environment.NewLine; return masterPageContent; } public string EnsureMasterPageSyntax(string masterPageContent) { ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", true); ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", false); // Parse the design for macros ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", true); ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", false); // Parse the design for load childs masterPageContent = masterPageContent.Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD/>", GetAspNetMasterPageContentContainer()).Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD />", GetAspNetMasterPageContentContainer()); // Parse the design for aspnet forms GetAspNetMasterPageForm(ref masterPageContent); masterPageContent = masterPageContent.Replace("</?ASPNET_FORM>", "</form>"); // Parse the design for aspnet heads masterPageContent = masterPageContent.Replace("</ASPNET_HEAD>", String.Format("<head id=\"{0}Head\" runat=\"server\">", Alias.Replace(" ", ""))); masterPageContent = masterPageContent.Replace("</?ASPNET_HEAD>", "</head>"); return masterPageContent; } public void ImportDesign(string design) { Design = design; } public void SaveMasterPageFile(string masterPageContent) { //this will trigger the helper and store everything this.Design = masterPageContent; } private void GetAspNetMasterPageForm(ref string design) { Match formElement = Regex.Match(design, GetElementRegExp("?ASPNET_FORM", false), RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); if (formElement != null && formElement.Value != "") { string formReplace = String.Format("<form id=\"{0}Form\" runat=\"server\">", Alias.Replace(" ", "")); if (formElement.Groups.Count == 0) { formReplace += "<asp:scriptmanager runat=\"server\"></asp:scriptmanager>"; } design = design.Replace(formElement.Value, formReplace); } } private string GetAspNetMasterPageContentContainer() { return String.Format( "<asp:ContentPlaceHolder ID=\"{0}ContentPlaceHolder\" runat=\"server\"></asp:ContentPlaceHolder>", Alias.Replace(" ", "")); } private void ReplaceElement(ref string design, string elementName, string newElementName, bool checkForQuotes) { MatchCollection m = Regex.Matches(design, GetElementRegExp(elementName, checkForQuotes), RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match match in m) { GroupCollection groups = match.Groups; // generate new element (compensate for a closing trail on single elements ("/")) string elementAttributes = groups[1].Value; // test for macro alias if (elementName == "?UMBRACO_MACRO") { Hashtable tags = helpers.xhtml.ReturnAttributes(match.Value); if (tags["macroAlias"] != null) elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroAlias"].ToString()) + elementAttributes; else if (tags["macroalias"] != null) elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroalias"].ToString()) + elementAttributes; } string newElement = "<" + newElementName + " runat=\"server\" " + elementAttributes.Trim() + ">"; if (elementAttributes.EndsWith("/")) { elementAttributes = elementAttributes.Substring(0, elementAttributes.Length - 1); } else if (groups[0].Value.StartsWith("</")) // It's a closing element, so generate that instead of a starting element newElement = "</" + newElementName + ">"; if (checkForQuotes) { // if it's inside quotes, we'll change element attribute quotes to single quotes newElement = newElement.Replace("\"", "'"); newElement = String.Format("\"{0}\"", newElement); } design = design.Replace(match.Value, newElement); } } private string GetElementRegExp(string elementName, bool checkForQuotes) { if (checkForQuotes) return String.Format("\"<[^>\\s]*\\b{0}(\\b[^>]*)>\"", elementName); else return String.Format("<[^>\\s]*\\b{0}(\\b[^>]*)>", elementName); } [Obsolete("Umbraco automatically ensures that template cache is cleared when saving or deleting")] protected virtual void FlushCache() { //ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id)); } public static Template GetTemplate(int id) { var found = ApplicationContext.Current.Services.FileService.GetTemplate(id); return found == null ? null : new Template(found); } public static Template Import(XmlNode n, User u) { var element = System.Xml.Linq.XElement.Parse(n.OuterXml); var templates = ApplicationContext.Current.Services.PackagingService.ImportTemplates(element, u.Id); return new Template(templates.First().Id); } #region Events //EVENTS /// <summary> /// The save event handler /// </summary> public delegate void SaveEventHandler(Template sender, SaveEventArgs e); /// <summary> /// The new event handler /// </summary> public delegate void NewEventHandler(Template sender, NewEventArgs e); /// <summary> /// The delete event handler /// </summary> public delegate void DeleteEventHandler(Template sender, DeleteEventArgs e); /// <summary> /// Occurs when [before save]. /// </summary> public new static event SaveEventHandler BeforeSave; /// <summary> /// Raises the <see cref="E:BeforeSave"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected override void FireBeforeSave(SaveEventArgs e) { if (BeforeSave != null) BeforeSave(this, e); } /// <summary> /// Occurs when [after save]. /// </summary> public new static event SaveEventHandler AfterSave; /// <summary> /// Raises the <see cref="E:AfterSave"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected override void FireAfterSave(SaveEventArgs e) { if (AfterSave != null) AfterSave(this, e); } /// <summary> /// Occurs when [new]. /// </summary> public static event NewEventHandler New; /// <summary> /// Raises the <see cref="E:New"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void OnNew(NewEventArgs e) { if (New != null) New(this, e); } /// <summary> /// Occurs when [before delete]. /// </summary> public new static event DeleteEventHandler BeforeDelete; /// <summary> /// Raises the <see cref="E:BeforeDelete"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected override void FireBeforeDelete(DeleteEventArgs e) { if (BeforeDelete != null) BeforeDelete(this, e); } /// <summary> /// Occurs when [after delete]. /// </summary> public new static event DeleteEventHandler AfterDelete; /// <summary> /// Raises the <see cref="E:AfterDelete"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected override void FireAfterDelete(DeleteEventArgs e) { if (AfterDelete != null) AfterDelete(this, e); } #endregion } }