context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.IO.Compression
{
internal sealed class InflaterManaged
{
// const tables used in decoding:
// Extra bits for length code 257 - 285.
private static readonly byte[] s_extraLengthBits =
{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,16 };
// The base length for length code 257 - 285.
// The formula to get the real length for a length code is lengthBase[code - 257] + (value stored in extraBits)
private static readonly int[] s_lengthBase =
{ 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,3};
// The base distance for distance code 0 - 31
// The real distance for a distance code is distanceBasePosition[code] + (value stored in extraBits)
private static readonly int[] s_distanceBasePosition =
{ 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,32769,49153 };
// code lengths for code length alphabet is stored in following order
private static readonly byte[] s_codeOrder = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
private static readonly byte[] s_staticDistanceTreeTable =
{
0x00,0x10,0x08,0x18,0x04,0x14,0x0c,0x1c,0x02,0x12,0x0a,0x1a,
0x06,0x16,0x0e,0x1e,0x01,0x11,0x09,0x19,0x05,0x15,0x0d,0x1d,
0x03,0x13,0x0b,0x1b,0x07,0x17,0x0f,0x1f
};
private readonly OutputWindow _output;
private readonly InputBuffer _input;
private HuffmanTree _literalLengthTree;
private HuffmanTree _distanceTree;
private InflaterState _state;
private bool _hasFormatReader;
private int _bfinal;
private BlockType _blockType;
// uncompressed block
private readonly byte[] _blockLengthBuffer = new byte[4];
private int _blockLength;
// compressed block
private int _length;
private int _distanceCode;
private int _extraBits;
private int _loopCounter;
private int _literalLengthCodeCount;
private int _distanceCodeCount;
private int _codeLengthCodeCount;
private int _codeArraySize;
private int _lengthCode;
private readonly byte[] _codeList; // temporary array to store the code length for literal/Length and distance
private readonly byte[] _codeLengthTreeCodeLength;
private readonly bool _deflate64;
private HuffmanTree _codeLengthTree;
private IFileFormatReader _formatReader; // class to decode header and footer (e.g. gzip)
internal InflaterManaged(IFileFormatReader reader, bool deflate64)
{
_output = new OutputWindow();
_input = new InputBuffer();
_codeList = new byte[HuffmanTree.MaxLiteralTreeElements + HuffmanTree.MaxDistTreeElements];
_codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements];
_deflate64 = deflate64;
if (reader != null)
{
_formatReader = reader;
_hasFormatReader = true;
}
Reset();
}
private void Reset()
{
_state = _hasFormatReader ?
InflaterState.ReadingHeader : // start by reading Header info
InflaterState.ReadingBFinal; // start by reading BFinal bit
}
public void SetInput(byte[] inputBytes, int offset, int length) =>
_input.SetInput(inputBytes, offset, length); // append the bytes
public bool Finished() => _state == InflaterState.Done || _state == InflaterState.VerifyingFooter;
public int AvailableOutput => _output.AvailableBytes;
public int Inflate(byte[] bytes, int offset, int length)
{
// copy bytes from output to outputbytes if we have available bytes
// if buffer is not filled up. keep decoding until no input are available
// if decodeBlock returns false. Throw an exception.
int count = 0;
do
{
int copied = _output.CopyTo(bytes, offset, length);
if (copied > 0)
{
if (_hasFormatReader)
{
_formatReader.UpdateWithBytesRead(bytes, offset, copied);
}
offset += copied;
count += copied;
length -= copied;
}
if (length == 0)
{ // filled in the bytes array
break;
}
// Decode will return false when more input is needed
} while (!Finished() && Decode());
if (_state == InflaterState.VerifyingFooter)
{ // finished reading CRC
// In this case finished is true and output window has all the data.
// But some data in output window might not be copied out.
if (_output.AvailableBytes == 0)
{
_formatReader.Validate();
}
}
return count;
}
//Each block of compressed data begins with 3 header bits
// containing the following data:
// first bit BFINAL
// next 2 bits BTYPE
// Note that the header bits do not necessarily begin on a byte
// boundary, since a block does not necessarily occupy an integral
// number of bytes.
// BFINAL is set if and only if this is the last block of the data
// set.
// BTYPE specifies how the data are compressed, as follows:
// 00 - no compression
// 01 - compressed with fixed Huffman codes
// 10 - compressed with dynamic Huffman codes
// 11 - reserved (error)
// The only difference between the two compressed cases is how the
// Huffman codes for the literal/length and distance alphabets are
// defined.
//
// This function returns true for success (end of block or output window is full,)
// false if we are short of input
//
private bool Decode()
{
bool eob = false;
bool result = false;
if (Finished())
{
return true;
}
if (_hasFormatReader)
{
if (_state == InflaterState.ReadingHeader)
{
if (!_formatReader.ReadHeader(_input))
{
return false;
}
_state = InflaterState.ReadingBFinal;
}
else if (_state == InflaterState.StartReadingFooter || _state == InflaterState.ReadingFooter)
{
if (!_formatReader.ReadFooter(_input))
return false;
_state = InflaterState.VerifyingFooter;
return true;
}
}
if (_state == InflaterState.ReadingBFinal)
{
// reading bfinal bit
// Need 1 bit
if (!_input.EnsureBitsAvailable(1))
return false;
_bfinal = _input.GetBits(1);
_state = InflaterState.ReadingBType;
}
if (_state == InflaterState.ReadingBType)
{
// Need 2 bits
if (!_input.EnsureBitsAvailable(2))
{
_state = InflaterState.ReadingBType;
return false;
}
_blockType = (BlockType)_input.GetBits(2);
if (_blockType == BlockType.Dynamic)
{
_state = InflaterState.ReadingNumLitCodes;
}
else if (_blockType == BlockType.Static)
{
_literalLengthTree = HuffmanTree.StaticLiteralLengthTree;
_distanceTree = HuffmanTree.StaticDistanceTree;
_state = InflaterState.DecodeTop;
}
else if (_blockType == BlockType.Uncompressed)
{
_state = InflaterState.UncompressedAligning;
}
else
{
throw new InvalidDataException(SR.UnknownBlockType);
}
}
if (_blockType == BlockType.Dynamic)
{
if (_state < InflaterState.DecodeTop)
{
// we are reading the header
result = DecodeDynamicBlockHeader();
}
else
{
result = DecodeBlock(out eob); // this can returns true when output is full
}
}
else if (_blockType == BlockType.Static)
{
result = DecodeBlock(out eob);
}
else if (_blockType == BlockType.Uncompressed)
{
result = DecodeUncompressedBlock(out eob);
}
else
{
throw new InvalidDataException(SR.UnknownBlockType);
}
//
// If we reached the end of the block and the block we were decoding had
// bfinal=1 (final block)
//
if (eob && (_bfinal != 0))
{
if (_hasFormatReader)
_state = InflaterState.StartReadingFooter;
else
_state = InflaterState.Done;
}
return result;
}
// Format of Non-compressed blocks (BTYPE=00):
//
// Any bits of input up to the next byte boundary are ignored.
// The rest of the block consists of the following information:
//
// 0 1 2 3 4...
// +---+---+---+---+================================+
// | LEN | NLEN |... LEN bytes of literal data...|
// +---+---+---+---+================================+
//
// LEN is the number of data bytes in the block. NLEN is the
// one's complement of LEN.
private bool DecodeUncompressedBlock(out bool end_of_block)
{
end_of_block = false;
while (true)
{
switch (_state)
{
case InflaterState.UncompressedAligning: // initial state when calling this function
// we must skip to a byte boundary
_input.SkipToByteBoundary();
_state = InflaterState.UncompressedByte1;
goto case InflaterState.UncompressedByte1;
case InflaterState.UncompressedByte1: // decoding block length
case InflaterState.UncompressedByte2:
case InflaterState.UncompressedByte3:
case InflaterState.UncompressedByte4:
int bits = _input.GetBits(8);
if (bits < 0)
{
return false;
}
_blockLengthBuffer[_state - InflaterState.UncompressedByte1] = (byte)bits;
if (_state == InflaterState.UncompressedByte4)
{
_blockLength = _blockLengthBuffer[0] + ((int)_blockLengthBuffer[1]) * 256;
int blockLengthComplement = _blockLengthBuffer[2] + ((int)_blockLengthBuffer[3]) * 256;
// make sure complement matches
if ((ushort)_blockLength != (ushort)(~blockLengthComplement))
{
throw new InvalidDataException(SR.InvalidBlockLength);
}
}
_state += 1;
break;
case InflaterState.DecodingUncompressed: // copying block data
// Directly copy bytes from input to output.
int bytesCopied = _output.CopyFrom(_input, _blockLength);
_blockLength -= bytesCopied;
if (_blockLength == 0)
{
// Done with this block, need to re-init bit buffer for next block
_state = InflaterState.ReadingBFinal;
end_of_block = true;
return true;
}
// We can fail to copy all bytes for two reasons:
// Running out of Input
// running out of free space in output window
if (_output.FreeBytes == 0)
{
return true;
}
return false;
default:
Debug.Fail("check why we are here!");
throw new InvalidDataException(SR.UnknownState);
}
}
}
private bool DecodeBlock(out bool end_of_block_code_seen)
{
end_of_block_code_seen = false;
int freeBytes = _output.FreeBytes; // it is a little bit faster than frequently accessing the property
while (freeBytes > 65536)
{
// With Deflate64 we can have up to a 64kb length, so we ensure at least that much space is available
// in the OutputWindow to avoid overwriting previous unflushed output data.
int symbol;
switch (_state)
{
case InflaterState.DecodeTop:
// decode an element from the literal tree
// TODO: optimize this!!!
symbol = _literalLengthTree.GetNextSymbol(_input);
if (symbol < 0)
{
// running out of input
return false;
}
if (symbol < 256)
{
// literal
_output.Write((byte)symbol);
--freeBytes;
}
else if (symbol == 256)
{
// end of block
end_of_block_code_seen = true;
// Reset state
_state = InflaterState.ReadingBFinal;
return true;
}
else
{
// length/distance pair
symbol -= 257; // length code started at 257
if (symbol < 8)
{
symbol += 3; // match length = 3,4,5,6,7,8,9,10
_extraBits = 0;
}
else if (!_deflate64 && symbol == 28)
{
// extra bits for code 285 is 0
symbol = 258; // code 285 means length 258
_extraBits = 0;
}
else
{
if (symbol < 0 || symbol >= s_extraLengthBits.Length)
{
throw new InvalidDataException(SR.GenericInvalidData);
}
_extraBits = s_extraLengthBits[symbol];
Debug.Assert(_extraBits != 0, "We handle other cases separately!");
}
_length = symbol;
goto case InflaterState.HaveInitialLength;
}
break;
case InflaterState.HaveInitialLength:
if (_extraBits > 0)
{
_state = InflaterState.HaveInitialLength;
int bits = _input.GetBits(_extraBits);
if (bits < 0)
{
return false;
}
if (_length < 0 || _length >= s_lengthBase.Length)
{
throw new InvalidDataException(SR.GenericInvalidData);
}
_length = s_lengthBase[_length] + bits;
}
_state = InflaterState.HaveFullLength;
goto case InflaterState.HaveFullLength;
case InflaterState.HaveFullLength:
if (_blockType == BlockType.Dynamic)
{
_distanceCode = _distanceTree.GetNextSymbol(_input);
}
else
{
// get distance code directly for static block
_distanceCode = _input.GetBits(5);
if (_distanceCode >= 0)
{
_distanceCode = s_staticDistanceTreeTable[_distanceCode];
}
}
if (_distanceCode < 0)
{
// running out input
return false;
}
_state = InflaterState.HaveDistCode;
goto case InflaterState.HaveDistCode;
case InflaterState.HaveDistCode:
// To avoid a table lookup we note that for distanceCode > 3,
// extra_bits = (distanceCode-2) >> 1
int offset;
if (_distanceCode > 3)
{
_extraBits = (_distanceCode - 2) >> 1;
int bits = _input.GetBits(_extraBits);
if (bits < 0)
{
return false;
}
offset = s_distanceBasePosition[_distanceCode] + bits;
}
else
{
offset = _distanceCode + 1;
}
_output.WriteLengthDistance(_length, offset);
freeBytes -= _length;
_state = InflaterState.DecodeTop;
break;
default:
Debug.Fail("check why we are here!");
throw new InvalidDataException(SR.UnknownState);
}
}
return true;
}
// Format of the dynamic block header:
// 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286)
// 5 Bits: HDIST, # of Distance codes - 1 (1 - 32)
// 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19)
//
// (HCLEN + 4) x 3 bits: code lengths for the code length
// alphabet given just above, in the order: 16, 17, 18,
// 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
//
// These code lengths are interpreted as 3-bit integers
// (0-7); as above, a code length of 0 means the
// corresponding symbol (literal/length or distance code
// length) is not used.
//
// HLIT + 257 code lengths for the literal/length alphabet,
// encoded using the code length Huffman code
//
// HDIST + 1 code lengths for the distance alphabet,
// encoded using the code length Huffman code
//
// The code length repeat codes can cross from HLIT + 257 to the
// HDIST + 1 code lengths. In other words, all code lengths form
// a single sequence of HLIT + HDIST + 258 values.
private bool DecodeDynamicBlockHeader()
{
switch (_state)
{
case InflaterState.ReadingNumLitCodes:
_literalLengthCodeCount = _input.GetBits(5);
if (_literalLengthCodeCount < 0)
{
return false;
}
_literalLengthCodeCount += 257;
_state = InflaterState.ReadingNumDistCodes;
goto case InflaterState.ReadingNumDistCodes;
case InflaterState.ReadingNumDistCodes:
_distanceCodeCount = _input.GetBits(5);
if (_distanceCodeCount < 0)
{
return false;
}
_distanceCodeCount += 1;
_state = InflaterState.ReadingNumCodeLengthCodes;
goto case InflaterState.ReadingNumCodeLengthCodes;
case InflaterState.ReadingNumCodeLengthCodes:
_codeLengthCodeCount = _input.GetBits(4);
if (_codeLengthCodeCount < 0)
{
return false;
}
_codeLengthCodeCount += 4;
_loopCounter = 0;
_state = InflaterState.ReadingCodeLengthCodes;
goto case InflaterState.ReadingCodeLengthCodes;
case InflaterState.ReadingCodeLengthCodes:
while (_loopCounter < _codeLengthCodeCount)
{
int bits = _input.GetBits(3);
if (bits < 0)
{
return false;
}
_codeLengthTreeCodeLength[s_codeOrder[_loopCounter]] = (byte)bits;
++_loopCounter;
}
for (int i = _codeLengthCodeCount; i < s_codeOrder.Length; i++)
{
_codeLengthTreeCodeLength[s_codeOrder[i]] = 0;
}
// create huffman tree for code length
_codeLengthTree = new HuffmanTree(_codeLengthTreeCodeLength);
_codeArraySize = _literalLengthCodeCount + _distanceCodeCount;
_loopCounter = 0; // reset loop count
_state = InflaterState.ReadingTreeCodesBefore;
goto case InflaterState.ReadingTreeCodesBefore;
case InflaterState.ReadingTreeCodesBefore:
case InflaterState.ReadingTreeCodesAfter:
while (_loopCounter < _codeArraySize)
{
if (_state == InflaterState.ReadingTreeCodesBefore)
{
if ((_lengthCode = _codeLengthTree.GetNextSymbol(_input)) < 0)
{
return false;
}
}
// The alphabet for code lengths is as follows:
// 0 - 15: Represent code lengths of 0 - 15
// 16: Copy the previous code length 3 - 6 times.
// The next 2 bits indicate repeat length
// (0 = 3, ... , 3 = 6)
// Example: Codes 8, 16 (+2 bits 11),
// 16 (+2 bits 10) will expand to
// 12 code lengths of 8 (1 + 6 + 5)
// 17: Repeat a code length of 0 for 3 - 10 times.
// (3 bits of length)
// 18: Repeat a code length of 0 for 11 - 138 times
// (7 bits of length)
if (_lengthCode <= 15)
{
_codeList[_loopCounter++] = (byte)_lengthCode;
}
else
{
int repeatCount;
if (_lengthCode == 16)
{
if (!_input.EnsureBitsAvailable(2))
{
_state = InflaterState.ReadingTreeCodesAfter;
return false;
}
if (_loopCounter == 0)
{
// can't have "prev code" on first code
throw new InvalidDataException();
}
byte previousCode = _codeList[_loopCounter - 1];
repeatCount = _input.GetBits(2) + 3;
if (_loopCounter + repeatCount > _codeArraySize)
{
throw new InvalidDataException();
}
for (int j = 0; j < repeatCount; j++)
{
_codeList[_loopCounter++] = previousCode;
}
}
else if (_lengthCode == 17)
{
if (!_input.EnsureBitsAvailable(3))
{
_state = InflaterState.ReadingTreeCodesAfter;
return false;
}
repeatCount = _input.GetBits(3) + 3;
if (_loopCounter + repeatCount > _codeArraySize)
{
throw new InvalidDataException();
}
for (int j = 0; j < repeatCount; j++)
{
_codeList[_loopCounter++] = 0;
}
}
else
{
// code == 18
if (!_input.EnsureBitsAvailable(7))
{
_state = InflaterState.ReadingTreeCodesAfter;
return false;
}
repeatCount = _input.GetBits(7) + 11;
if (_loopCounter + repeatCount > _codeArraySize)
{
throw new InvalidDataException();
}
for (int j = 0; j < repeatCount; j++)
{
_codeList[_loopCounter++] = 0;
}
}
}
_state = InflaterState.ReadingTreeCodesBefore; // we want to read the next code.
}
break;
default:
Debug.Fail("check why we are here!");
throw new InvalidDataException(SR.UnknownState);
}
byte[] literalTreeCodeLength = new byte[HuffmanTree.MaxLiteralTreeElements];
byte[] distanceTreeCodeLength = new byte[HuffmanTree.MaxDistTreeElements];
// Create literal and distance tables
Array.Copy(_codeList, 0, literalTreeCodeLength, 0, _literalLengthCodeCount);
Array.Copy(_codeList, _literalLengthCodeCount, distanceTreeCodeLength, 0, _distanceCodeCount);
// Make sure there is an end-of-block code, otherwise how could we ever end?
if (literalTreeCodeLength[HuffmanTree.EndOfBlockCode] == 0)
{
throw new InvalidDataException();
}
_literalLengthTree = new HuffmanTree(literalTreeCodeLength);
_distanceTree = new HuffmanTree(distanceTreeCodeLength);
_state = InflaterState.DecodeTop;
return true;
}
public void Dispose() { }
}
}
| |
using System;
using MS.Internal.WindowsBase;
namespace System.Windows.Threading
{
/// <summary>
/// Represents a range of priorities.
/// </summary>
internal struct PriorityRange
{
/// <summary>
/// The range of all possible priorities.
/// </summary>
public static readonly PriorityRange All = new PriorityRange(DispatcherPriority.Inactive, DispatcherPriority.Send, true); // NOTE: should be Priority
/// <summary>
/// A range that includes no priorities.
/// </summary>
public static readonly PriorityRange None = new PriorityRange(DispatcherPriority.Invalid, DispatcherPriority.Invalid, true); // NOTE: should be Priority
/// <summary>
/// Constructs an instance of the PriorityRange class.
/// </summary>
public PriorityRange(DispatcherPriority min, DispatcherPriority max) : this() // NOTE: should be Priority
{
Initialize(min, true, max, true);
}
/// <summary>
/// Constructs an instance of the PriorityRange class.
/// </summary>
public PriorityRange(DispatcherPriority min, bool isMinInclusive, DispatcherPriority max, bool isMaxInclusive) : this() // NOTE: should be Priority
{
Initialize(min, isMinInclusive, max, isMaxInclusive);
}
/// <summary>
/// The minimum priority of this range.
/// </summary>
public DispatcherPriority Min // NOTE: should be Priority
{
get
{
return _min;
}
}
/// <summary>
/// The maximum priority of this range.
/// </summary>
public DispatcherPriority Max // NOTE: should be Priority
{
get
{
return _max;
}
}
/// <summary>
/// Whether or not the minimum priority in included in this range.
/// </summary>
public bool IsMinInclusive
{
get
{
return _isMinInclusive;
}
}
/// <summary>
/// Whether or not the maximum priority in included in this range.
/// </summary>
public bool IsMaxInclusive
{
get
{
return _isMaxInclusive;
}
}
/// <summary>
/// Whether or not this priority range is valid.
/// </summary>
public bool IsValid
{
get
{
// return _min != null && _min.IsValid && _max != null && _max.IsValid;
return (_min > DispatcherPriority.Invalid && _min <= DispatcherPriority.Send &&
_max > DispatcherPriority.Invalid && _max <= DispatcherPriority.Send);
}
}
/// <summary>
/// Whether or not this priority range contains the specified
/// priority.
/// </summary>
public bool Contains(DispatcherPriority priority) // NOTE: should be Priority
{
/*
if (priority == null || !priority.IsValid)
{
return false;
}
*/
if(priority <= DispatcherPriority.Invalid || priority > DispatcherPriority.Send)
{
return false;
}
if (!IsValid)
{
return false;
}
bool contains = false;
if (_isMinInclusive)
{
contains = (priority >= _min);
}
else
{
contains = (priority > _min);
}
if (contains)
{
if (_isMaxInclusive)
{
contains = (priority <= _max);
}
else
{
contains = (priority < _max);
}
}
return contains;
}
/// <summary>
/// Whether or not this priority range contains the specified
/// priority range.
/// </summary>
public bool Contains(PriorityRange priorityRange)
{
if (!priorityRange.IsValid)
{
return false;
}
if (!IsValid)
{
return false;
}
bool contains = false;
if (priorityRange._isMinInclusive)
{
contains = Contains(priorityRange.Min);
}
else
{
if(priorityRange.Min >= _min && priorityRange.Min < _max)
{
contains = true;
}
}
if (contains)
{
if (priorityRange._isMaxInclusive)
{
contains = Contains(priorityRange.Max);
}
else
{
if(priorityRange.Max > _min && priorityRange.Max <= _max)
{
contains = true;
}
}
}
return contains;
}
/// <summary>
/// Equality method for two PriorityRange
/// </summary>
public override bool Equals(object o)
{
if(o is PriorityRange)
{
return Equals((PriorityRange) o);
}
else
{
return false;
}
}
/// <summary>
/// Equality method for two PriorityRange
/// </summary>
public bool Equals(PriorityRange priorityRange)
{
return priorityRange._min == this._min &&
priorityRange._isMinInclusive == this._isMinInclusive &&
priorityRange._max == this._max &&
priorityRange._isMaxInclusive == this._isMaxInclusive;
}
/// <summary>
/// Equality operator
/// </summary>
public static bool operator== (PriorityRange priorityRange1, PriorityRange priorityRange2)
{
return priorityRange1.Equals(priorityRange2);
}
/// <summary>
/// Inequality operator
/// </summary>
public static bool operator!= (PriorityRange priorityRange1, PriorityRange priorityRange2)
{
return !(priorityRange1 == priorityRange2);
}
/// <summary>
/// Returns a reasonable hash code for this PriorityRange instance.
/// </summary>
public override int GetHashCode()
{
return base.GetHashCode();
}
private void Initialize(DispatcherPriority min, bool isMinInclusive, DispatcherPriority max, bool isMaxInclusive) // NOTE: should be Priority
{
/*
if(min == null)
{
throw new ArgumentNullException("min");
}
if (!min.IsValid)
{
throw new ArgumentException("Invalid priority.", "min");
}
*/
if(min < DispatcherPriority.Invalid || min > DispatcherPriority.Send)
{
// If we move to a Priority class, this exception will have to change too.
throw new System.ComponentModel.InvalidEnumArgumentException("min", (int)min, typeof(DispatcherPriority));
}
if(min == DispatcherPriority.Inactive)
{
throw new ArgumentException(SR.Get(SRID.InvalidPriority), "min");
}
/*
if(max == null)
{
throw new ArgumentNullException("max");
}
if (!max.IsValid)
{
throw new ArgumentException("Invalid priority.", "max");
}
*/
if(max < DispatcherPriority.Invalid || max > DispatcherPriority.Send)
{
// If we move to a Priority class, this exception will have to change too.
throw new System.ComponentModel.InvalidEnumArgumentException("max", (int)max, typeof(DispatcherPriority));
}
if(max == DispatcherPriority.Inactive)
{
throw new ArgumentException(SR.Get(SRID.InvalidPriority), "max");
}
if (max < min)
{
throw new ArgumentException(SR.Get(SRID.InvalidPriorityRangeOrder));
}
_min = min;
_isMinInclusive = isMinInclusive;
_max = max;
_isMaxInclusive = isMaxInclusive;
}
// This is a constructor for our special static members.
private PriorityRange(DispatcherPriority min, DispatcherPriority max, bool ignored) // NOTE: should be Priority
{
_min = min;
_isMinInclusive = true;
_max = max;
_isMaxInclusive = true;
}
private DispatcherPriority _min; // NOTE: should be Priority
private bool _isMinInclusive;
private DispatcherPriority _max; // NOTE: should be Priority
private bool _isMaxInclusive;
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmMainHO
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmMainHO() : base()
{
Load += frmMainHO_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_Command3;
public System.Windows.Forms.Button Command3 {
get { return withEventsField_Command3; }
set {
if (withEventsField_Command3 != null) {
withEventsField_Command3.Click -= Command3_Click;
}
withEventsField_Command3 = value;
if (withEventsField_Command3 != null) {
withEventsField_Command3.Click += Command3_Click;
}
}
}
public System.Windows.Forms.PictureBox picInner;
public System.Windows.Forms.Panel picOuter;
private System.Windows.Forms.Timer withEventsField_tmrAutoDE;
public System.Windows.Forms.Timer tmrAutoDE {
get { return withEventsField_tmrAutoDE; }
set {
if (withEventsField_tmrAutoDE != null) {
withEventsField_tmrAutoDE.Tick -= tmrAutoDE_Tick;
}
withEventsField_tmrAutoDE = value;
if (withEventsField_tmrAutoDE != null) {
withEventsField_tmrAutoDE.Tick += tmrAutoDE_Tick;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdBookIN;
public System.Windows.Forms.Button cmdBookIN {
get { return withEventsField_cmdBookIN; }
set {
if (withEventsField_cmdBookIN != null) {
withEventsField_cmdBookIN.Click -= cmdBookIN_Click;
}
withEventsField_cmdBookIN = value;
if (withEventsField_cmdBookIN != null) {
withEventsField_cmdBookIN.Click += cmdBookIN_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdBookOut;
public System.Windows.Forms.Button cmdBookOut {
get { return withEventsField_cmdBookOut; }
set {
if (withEventsField_cmdBookOut != null) {
withEventsField_cmdBookOut.Click -= cmdBookOut_Click;
}
withEventsField_cmdBookOut = value;
if (withEventsField_cmdBookOut != null) {
withEventsField_cmdBookOut.Click += cmdBookOut_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdUpReport;
public System.Windows.Forms.Button cmdUpReport {
get { return withEventsField_cmdUpReport; }
set {
if (withEventsField_cmdUpReport != null) {
withEventsField_cmdUpReport.Click -= cmdUpReport_Click;
}
withEventsField_cmdUpReport = value;
if (withEventsField_cmdUpReport != null) {
withEventsField_cmdUpReport.Click += cmdUpReport_Click;
}
}
}
public System.Windows.Forms.TextBox txtPrevOrder;
private System.Windows.Forms.Button withEventsField_Command1;
public System.Windows.Forms.Button Command1 {
get { return withEventsField_Command1; }
set {
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click -= Command1_Click;
}
withEventsField_Command1 = value;
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click += Command1_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdToday;
public System.Windows.Forms.Button cmdToday {
get { return withEventsField_cmdToday; }
set {
if (withEventsField_cmdToday != null) {
withEventsField_cmdToday.Click -= cmdToday_Click;
}
withEventsField_cmdToday = value;
if (withEventsField_cmdToday != null) {
withEventsField_cmdToday.Click += cmdToday_Click;
}
}
}
public DateTimePicker _DTPicker1_0;
public DateTimePicker _DTPicker1_1;
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.Panel Picture1;
public System.Windows.Forms.TextBox Text4;
public System.Windows.Forms.TextBox Text3;
public System.Windows.Forms.TextBox Text2;
public System.Windows.Forms.Button _cmdPulsante_5;
private System.Windows.Forms.Button withEventsField_cmdClearLock;
public System.Windows.Forms.Button cmdClearLock {
get { return withEventsField_cmdClearLock; }
set {
if (withEventsField_cmdClearLock != null) {
withEventsField_cmdClearLock.Click -= cmdClearLock_Click;
}
withEventsField_cmdClearLock = value;
if (withEventsField_cmdClearLock != null) {
withEventsField_cmdClearLock.Click += cmdClearLock_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_Command2;
public System.Windows.Forms.Button Command2 {
get { return withEventsField_Command2; }
set {
if (withEventsField_Command2 != null) {
withEventsField_Command2.Click -= Command2_Click;
}
withEventsField_Command2 = value;
if (withEventsField_Command2 != null) {
withEventsField_Command2.Click += Command2_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdCheckWOrder;
public System.Windows.Forms.Button cmdCheckWOrder {
get { return withEventsField_cmdCheckWOrder; }
set {
if (withEventsField_cmdCheckWOrder != null) {
withEventsField_cmdCheckWOrder.Click -= cmdCheckWOrder_Click;
}
withEventsField_cmdCheckWOrder = value;
if (withEventsField_cmdCheckWOrder != null) {
withEventsField_cmdCheckWOrder.Click += cmdCheckWOrder_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.TextBox Text1;
public System.Windows.Forms.Label _Label1_1;
public System.Windows.Forms.GroupBox _Frame1_0;
public System.Windows.Forms.Button _cmdPulsante_7;
public System.Windows.Forms.Button _cmdPulsante_6;
public System.Windows.Forms.GroupBox _Frame1_3;
public System.Windows.Forms.Button _cmdPulsante_4;
public System.Windows.Forms.GroupBox _Frame1_2;
public System.Windows.Forms.Button _cmdPulsante_3;
public System.Windows.Forms.Button _cmdPulsante_2;
public System.Windows.Forms.Button _cmdPulsante_1;
public System.Windows.Forms.Button _cmdPulsante_0;
public System.Windows.Forms.GroupBox _Frame1_1;
public System.Windows.Forms.Label lbl8;
public System.Windows.Forms.Label lbl11;
public System.Windows.Forms.Label lbl55;
public System.Windows.Forms.Label lbl5;
public System.Windows.Forms.Label lbl44;
public System.Windows.Forms.Label lbl4;
public System.Windows.Forms.Label lbl33;
public System.Windows.Forms.Label lbl3;
public System.Windows.Forms.Label lbl22;
public System.Windows.Forms.Label lbl2;
public System.Windows.Forms.Label lbl1;
public System.Windows.Forms.Label lbl66;
public System.Windows.Forms.Label lbl6;
//Public WithEvents DTPicker1 As System.Windows.Forms.DateTimePicker
//Public WithEvents Frame1 As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
//Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents cmdPulsante As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMainHO));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.Command3 = new System.Windows.Forms.Button();
this.picOuter = new System.Windows.Forms.Panel();
this.picInner = new System.Windows.Forms.PictureBox();
this.tmrAutoDE = new System.Windows.Forms.Timer(components);
this.cmdBookIN = new System.Windows.Forms.Button();
this.cmdBookOut = new System.Windows.Forms.Button();
this.cmdUpReport = new System.Windows.Forms.Button();
this.txtPrevOrder = new System.Windows.Forms.TextBox();
this.Command1 = new System.Windows.Forms.Button();
this.cmdExit = new System.Windows.Forms.Button();
this.Picture1 = new System.Windows.Forms.Panel();
this.cmdToday = new System.Windows.Forms.Button();
this._DTPicker1_0 = new System.Windows.Forms.DateTimePicker();
this._DTPicker1_1 = new System.Windows.Forms.DateTimePicker();
this._lbl_0 = new System.Windows.Forms.Label();
this.Text4 = new System.Windows.Forms.TextBox();
this.Text3 = new System.Windows.Forms.TextBox();
this.Text2 = new System.Windows.Forms.TextBox();
this._cmdPulsante_5 = new System.Windows.Forms.Button();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdClearLock = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this.Command2 = new System.Windows.Forms.Button();
this.cmdCheckWOrder = new System.Windows.Forms.Button();
this._Frame1_0 = new System.Windows.Forms.GroupBox();
this.Text1 = new System.Windows.Forms.TextBox();
this._Label1_1 = new System.Windows.Forms.Label();
this._Frame1_3 = new System.Windows.Forms.GroupBox();
this._cmdPulsante_7 = new System.Windows.Forms.Button();
this._cmdPulsante_6 = new System.Windows.Forms.Button();
this._Frame1_2 = new System.Windows.Forms.GroupBox();
this._cmdPulsante_4 = new System.Windows.Forms.Button();
this._Frame1_1 = new System.Windows.Forms.GroupBox();
this._cmdPulsante_3 = new System.Windows.Forms.Button();
this._cmdPulsante_2 = new System.Windows.Forms.Button();
this._cmdPulsante_1 = new System.Windows.Forms.Button();
this._cmdPulsante_0 = new System.Windows.Forms.Button();
this.lbl8 = new System.Windows.Forms.Label();
this.lbl11 = new System.Windows.Forms.Label();
this.lbl55 = new System.Windows.Forms.Label();
this.lbl5 = new System.Windows.Forms.Label();
this.lbl44 = new System.Windows.Forms.Label();
this.lbl4 = new System.Windows.Forms.Label();
this.lbl33 = new System.Windows.Forms.Label();
this.lbl3 = new System.Windows.Forms.Label();
this.lbl22 = new System.Windows.Forms.Label();
this.lbl2 = new System.Windows.Forms.Label();
this.lbl1 = new System.Windows.Forms.Label();
this.lbl66 = new System.Windows.Forms.Label();
this.lbl6 = new System.Windows.Forms.Label();
//Me.DTPicker1 = New System.Windows.Forms.DateTimePicker
//Me.Frame1 = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components)
//Me.Label1 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.cmdPulsante = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.picOuter.SuspendLayout();
this.Picture1.SuspendLayout();
this.picButtons.SuspendLayout();
this._Frame1_0.SuspendLayout();
this._Frame1_3.SuspendLayout();
this._Frame1_2.SuspendLayout();
this._Frame1_1.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this._DTPicker1_0).BeginInit();
((System.ComponentModel.ISupportInitialize)this._DTPicker1_1).BeginInit();
//CType(Me.DTPicker1, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.Frame1, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.Label1, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.cmdPulsante, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "4POS HeadOffice Sync Engine";
this.ClientSize = new System.Drawing.Size(473, 602);
this.Location = new System.Drawing.Point(3, 29);
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmMainHO";
this.Command3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Command3.Text = " Prod perfor";
this.Command3.Size = new System.Drawing.Size(97, 27);
this.Command3.Location = new System.Drawing.Point(368, 232);
this.Command3.TabIndex = 48;
this.Command3.Visible = false;
this.Command3.BackColor = System.Drawing.SystemColors.Control;
this.Command3.CausesValidation = true;
this.Command3.Enabled = true;
this.Command3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Command3.Cursor = System.Windows.Forms.Cursors.Default;
this.Command3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Command3.TabStop = true;
this.Command3.Name = "Command3";
this.picOuter.BackColor = System.Drawing.Color.White;
this.picOuter.Size = new System.Drawing.Size(425, 33);
this.picOuter.Location = new System.Drawing.Point(24, 392);
this.picOuter.TabIndex = 46;
this.picOuter.Visible = false;
this.picOuter.Dock = System.Windows.Forms.DockStyle.None;
this.picOuter.CausesValidation = true;
this.picOuter.Enabled = true;
this.picOuter.ForeColor = System.Drawing.SystemColors.ControlText;
this.picOuter.Cursor = System.Windows.Forms.Cursors.Default;
this.picOuter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picOuter.TabStop = true;
this.picOuter.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picOuter.Name = "picOuter";
this.picInner.BackColor = System.Drawing.Color.FromArgb(0, 0, 192);
this.picInner.ForeColor = System.Drawing.SystemColors.WindowText;
this.picInner.Size = new System.Drawing.Size(58, 34);
this.picInner.Location = new System.Drawing.Point(0, 0);
this.picInner.TabIndex = 47;
this.picInner.Dock = System.Windows.Forms.DockStyle.None;
this.picInner.CausesValidation = true;
this.picInner.Enabled = true;
this.picInner.Cursor = System.Windows.Forms.Cursors.Default;
this.picInner.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picInner.TabStop = true;
this.picInner.Visible = true;
this.picInner.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal;
this.picInner.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.picInner.Name = "picInner";
this.tmrAutoDE.Enabled = false;
this.tmrAutoDE.Interval = 10;
this.cmdBookIN.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdBookIN.Text = "&Book In DB";
this.cmdBookIN.Size = new System.Drawing.Size(97, 27);
this.cmdBookIN.Location = new System.Drawing.Point(368, 112);
this.cmdBookIN.TabIndex = 44;
this.cmdBookIN.BackColor = System.Drawing.SystemColors.Control;
this.cmdBookIN.CausesValidation = true;
this.cmdBookIN.Enabled = true;
this.cmdBookIN.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBookIN.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBookIN.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBookIN.TabStop = true;
this.cmdBookIN.Name = "cmdBookIN";
this.cmdBookOut.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdBookOut.Text = "&Book Out DB";
this.cmdBookOut.Size = new System.Drawing.Size(97, 27);
this.cmdBookOut.Location = new System.Drawing.Point(368, 80);
this.cmdBookOut.TabIndex = 43;
this.cmdBookOut.BackColor = System.Drawing.SystemColors.Control;
this.cmdBookOut.CausesValidation = true;
this.cmdBookOut.Enabled = true;
this.cmdBookOut.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBookOut.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBookOut.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBookOut.TabStop = true;
this.cmdBookOut.Name = "cmdBookOut";
this.cmdUpReport.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdUpReport.Text = "&Upload Reports";
this.cmdUpReport.Size = new System.Drawing.Size(97, 27);
this.cmdUpReport.Location = new System.Drawing.Point(368, 48);
this.cmdUpReport.TabIndex = 42;
this.cmdUpReport.BackColor = System.Drawing.SystemColors.Control;
this.cmdUpReport.CausesValidation = true;
this.cmdUpReport.Enabled = true;
this.cmdUpReport.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdUpReport.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdUpReport.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdUpReport.TabStop = true;
this.cmdUpReport.Name = "cmdUpReport";
this.txtPrevOrder.AutoSize = false;
this.txtPrevOrder.Size = new System.Drawing.Size(129, 25);
this.txtPrevOrder.Location = new System.Drawing.Point(504, 552);
this.txtPrevOrder.TabIndex = 41;
this.txtPrevOrder.Text = "response";
this.txtPrevOrder.Visible = false;
this.txtPrevOrder.AcceptsReturn = true;
this.txtPrevOrder.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtPrevOrder.BackColor = System.Drawing.SystemColors.Window;
this.txtPrevOrder.CausesValidation = true;
this.txtPrevOrder.Enabled = true;
this.txtPrevOrder.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtPrevOrder.HideSelection = true;
this.txtPrevOrder.ReadOnly = false;
this.txtPrevOrder.MaxLength = 0;
this.txtPrevOrder.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtPrevOrder.Multiline = false;
this.txtPrevOrder.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtPrevOrder.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtPrevOrder.TabStop = true;
this.txtPrevOrder.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtPrevOrder.Name = "txtPrevOrder";
this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Command1.Text = "-";
this.Command1.Font = new System.Drawing.Font("Arial", 13.5f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Command1.Size = new System.Drawing.Size(35, 27);
this.Command1.Location = new System.Drawing.Point(488, 554);
this.Command1.TabIndex = 40;
this.Command1.BackColor = System.Drawing.SystemColors.Control;
this.Command1.CausesValidation = true;
this.Command1.Enabled = true;
this.Command1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Command1.Cursor = System.Windows.Forms.Cursors.Default;
this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Command1.TabStop = true;
this.Command1.Name = "Command1";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "X";
this.cmdExit.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdExit.Size = new System.Drawing.Size(35, 27);
this.cmdExit.Location = new System.Drawing.Point(528, 554);
this.cmdExit.TabIndex = 39;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.TabStop = true;
this.cmdExit.Name = "cmdExit";
this.Picture1.Size = new System.Drawing.Size(353, 33);
this.Picture1.Location = new System.Drawing.Point(8, 40);
this.Picture1.TabIndex = 34;
this.Picture1.Dock = System.Windows.Forms.DockStyle.None;
this.Picture1.BackColor = System.Drawing.SystemColors.Control;
this.Picture1.CausesValidation = true;
this.Picture1.Enabled = true;
this.Picture1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Picture1.Cursor = System.Windows.Forms.Cursors.Default;
this.Picture1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Picture1.TabStop = true;
this.Picture1.Visible = true;
this.Picture1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Picture1.Name = "Picture1";
this.cmdToday.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdToday.Text = "&1. Goto Yesterday";
this.cmdToday.Size = new System.Drawing.Size(102, 19);
this.cmdToday.Location = new System.Drawing.Point(248, 8);
this.cmdToday.TabIndex = 37;
this.cmdToday.TabStop = false;
this.cmdToday.BackColor = System.Drawing.SystemColors.Control;
this.cmdToday.CausesValidation = true;
this.cmdToday.Enabled = true;
this.cmdToday.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdToday.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdToday.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdToday.Name = "cmdToday";
//_DTPicker1_0.OcxState = CType(resources.GetObject("_DTPicker1_0.OcxState"), System.Windows.Forms.AxHost.State)
this._DTPicker1_0.Size = new System.Drawing.Size(94, 18);
this._DTPicker1_0.Location = new System.Drawing.Point(56, 8);
this._DTPicker1_0.TabIndex = 35;
this._DTPicker1_0.Visible = false;
this._DTPicker1_0.Name = "_DTPicker1_0";
//_DTPicker1_1.OcxState = CType(resources.GetObject("_DTPicker1_1.OcxState"), System.Windows.Forms.AxHost.State)
this._DTPicker1_1.Size = new System.Drawing.Size(86, 18);
this._DTPicker1_1.Location = new System.Drawing.Point(160, 8);
this._DTPicker1_1.TabIndex = 45;
this._DTPicker1_1.Name = "_DTPicker1_1";
this._lbl_0.Text = "Select Day to Upload Reports";
this._lbl_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_0.ForeColor = System.Drawing.Color.Black;
this._lbl_0.Size = new System.Drawing.Size(157, 14);
this._lbl_0.Location = new System.Drawing.Point(0, 8);
this._lbl_0.TabIndex = 36;
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Enabled = true;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = true;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_0.Name = "_lbl_0";
this.Text4.AutoSize = false;
this.Text4.BackColor = System.Drawing.Color.White;
this.Text4.ForeColor = System.Drawing.Color.Black;
this.Text4.Size = new System.Drawing.Size(249, 41);
this.Text4.Location = new System.Drawing.Point(480, 176);
this.Text4.ReadOnly = true;
this.Text4.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.Text4.WordWrap = false;
this.Text4.TabIndex = 32;
this.Text4.Text = "Text1";
this.Text4.AcceptsReturn = true;
this.Text4.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.Text4.CausesValidation = true;
this.Text4.Enabled = true;
this.Text4.HideSelection = true;
this.Text4.MaxLength = 0;
this.Text4.Cursor = System.Windows.Forms.Cursors.IBeam;
this.Text4.Multiline = false;
this.Text4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Text4.TabStop = true;
this.Text4.Visible = true;
this.Text4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Text4.Name = "Text4";
this.Text3.AutoSize = false;
this.Text3.BackColor = System.Drawing.Color.White;
this.Text3.ForeColor = System.Drawing.Color.Black;
this.Text3.Size = new System.Drawing.Size(249, 41);
this.Text3.Location = new System.Drawing.Point(480, 128);
this.Text3.ReadOnly = true;
this.Text3.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.Text3.WordWrap = false;
this.Text3.TabIndex = 31;
this.Text3.Text = "Text1";
this.Text3.AcceptsReturn = true;
this.Text3.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.Text3.CausesValidation = true;
this.Text3.Enabled = true;
this.Text3.HideSelection = true;
this.Text3.MaxLength = 0;
this.Text3.Cursor = System.Windows.Forms.Cursors.IBeam;
this.Text3.Multiline = false;
this.Text3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Text3.TabStop = true;
this.Text3.Visible = true;
this.Text3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Text3.Name = "Text3";
this.Text2.AutoSize = false;
this.Text2.BackColor = System.Drawing.Color.White;
this.Text2.ForeColor = System.Drawing.Color.Black;
this.Text2.Size = new System.Drawing.Size(249, 41);
this.Text2.Location = new System.Drawing.Point(480, 80);
this.Text2.ReadOnly = true;
this.Text2.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.Text2.WordWrap = false;
this.Text2.TabIndex = 30;
this.Text2.Text = "Text1";
this.Text2.AcceptsReturn = true;
this.Text2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.Text2.CausesValidation = true;
this.Text2.Enabled = true;
this.Text2.HideSelection = true;
this.Text2.MaxLength = 0;
this.Text2.Cursor = System.Windows.Forms.Cursors.IBeam;
this.Text2.Multiline = false;
this.Text2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Text2.TabStop = true;
this.Text2.Visible = true;
this.Text2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Text2.Name = "Text2";
this._cmdPulsante_5.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this._cmdPulsante_5.Text = "&Log";
this._cmdPulsante_5.Size = new System.Drawing.Size(97, 57);
this._cmdPulsante_5.Location = new System.Drawing.Point(616, 216);
this._cmdPulsante_5.Image = (System.Drawing.Image)resources.GetObject("_cmdPulsante_5.Image");
this._cmdPulsante_5.TabIndex = 14;
this._cmdPulsante_5.BackColor = System.Drawing.SystemColors.Control;
this._cmdPulsante_5.CausesValidation = true;
this._cmdPulsante_5.Enabled = true;
this._cmdPulsante_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdPulsante_5.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdPulsante_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdPulsante_5.TabStop = true;
this._cmdPulsante_5.Name = "_cmdPulsante_5";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(473, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 13;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdClearLock.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClearLock.Text = "Clear Log";
this.cmdClearLock.Size = new System.Drawing.Size(73, 29);
this.cmdClearLock.Location = new System.Drawing.Point(552, 4);
this.cmdClearLock.TabIndex = 38;
this.cmdClearLock.TabStop = false;
this.cmdClearLock.BackColor = System.Drawing.SystemColors.Control;
this.cmdClearLock.CausesValidation = true;
this.cmdClearLock.Enabled = true;
this.cmdClearLock.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClearLock.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClearLock.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClearLock.Name = "cmdClearLock";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(392, 4);
this.cmdClose.TabIndex = 33;
this.cmdClose.TabStop = false;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Name = "cmdClose";
this.Command2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Command2.Text = "&Download Pricing";
this.Command2.Size = new System.Drawing.Size(97, 27);
this.Command2.Location = new System.Drawing.Point(112, 4);
this.Command2.TabIndex = 29;
this.Command2.BackColor = System.Drawing.SystemColors.Control;
this.Command2.CausesValidation = true;
this.Command2.Enabled = true;
this.Command2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Command2.Cursor = System.Windows.Forms.Cursors.Default;
this.Command2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Command2.TabStop = true;
this.Command2.Name = "Command2";
this.cmdCheckWOrder.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdCheckWOrder.Text = "&Upload Pricing";
this.cmdCheckWOrder.Size = new System.Drawing.Size(97, 27);
this.cmdCheckWOrder.Location = new System.Drawing.Point(8, 4);
this.cmdCheckWOrder.TabIndex = 28;
this.cmdCheckWOrder.BackColor = System.Drawing.SystemColors.Control;
this.cmdCheckWOrder.CausesValidation = true;
this.cmdCheckWOrder.Enabled = true;
this.cmdCheckWOrder.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCheckWOrder.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCheckWOrder.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCheckWOrder.TabStop = true;
this.cmdCheckWOrder.Name = "cmdCheckWOrder";
this._Frame1_0.Size = new System.Drawing.Size(457, 313);
this._Frame1_0.Location = new System.Drawing.Point(8, 280);
this._Frame1_0.TabIndex = 10;
this._Frame1_0.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_0.Enabled = true;
this._Frame1_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_0.Visible = true;
this._Frame1_0.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_0.Name = "_Frame1_0";
this.Text1.AutoSize = false;
this.Text1.BackColor = System.Drawing.Color.White;
this.Text1.ForeColor = System.Drawing.Color.Black;
this.Text1.Size = new System.Drawing.Size(441, 257);
this.Text1.Location = new System.Drawing.Point(8, 16);
this.Text1.ReadOnly = true;
this.Text1.Multiline = true;
this.Text1.TabIndex = 11;
this.Text1.Text = "Text1";
this.Text1.AcceptsReturn = true;
this.Text1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.Text1.CausesValidation = true;
this.Text1.Enabled = true;
this.Text1.HideSelection = true;
this.Text1.MaxLength = 0;
this.Text1.Cursor = System.Windows.Forms.Cursors.IBeam;
this.Text1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Text1.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.Text1.TabStop = true;
this.Text1.Visible = true;
this.Text1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Text1.Name = "Text1";
this._Label1_1.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._Label1_1.Text = "File Name";
this._Label1_1.Size = new System.Drawing.Size(433, 25);
this._Label1_1.Location = new System.Drawing.Point(8, 280);
this._Label1_1.TabIndex = 12;
this._Label1_1.BackColor = System.Drawing.SystemColors.Control;
this._Label1_1.Enabled = true;
this._Label1_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label1_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label1_1.UseMnemonic = true;
this._Label1_1.Visible = true;
this._Label1_1.AutoSize = false;
this._Label1_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label1_1.Name = "_Label1_1";
this._Frame1_3.Size = new System.Drawing.Size(369, 81);
this._Frame1_3.Location = new System.Drawing.Point(488, 464);
this._Frame1_3.TabIndex = 7;
this._Frame1_3.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_3.Enabled = true;
this._Frame1_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_3.Visible = true;
this._Frame1_3.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_3.Name = "_Frame1_3";
this._cmdPulsante_7.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this._cmdPulsante_7.Text = "&Download";
this._cmdPulsante_7.Size = new System.Drawing.Size(145, 57);
this._cmdPulsante_7.Location = new System.Drawing.Point(208, 16);
this._cmdPulsante_7.Image = (System.Drawing.Image)resources.GetObject("_cmdPulsante_7.Image");
this._cmdPulsante_7.TabIndex = 9;
this._cmdPulsante_7.BackColor = System.Drawing.SystemColors.Control;
this._cmdPulsante_7.CausesValidation = true;
this._cmdPulsante_7.Enabled = true;
this._cmdPulsante_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdPulsante_7.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdPulsante_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdPulsante_7.TabStop = true;
this._cmdPulsante_7.Name = "_cmdPulsante_7";
this._cmdPulsante_6.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this._cmdPulsante_6.Text = "&Upload";
this._cmdPulsante_6.Size = new System.Drawing.Size(97, 57);
this._cmdPulsante_6.Location = new System.Drawing.Point(72, 16);
this._cmdPulsante_6.Image = (System.Drawing.Image)resources.GetObject("_cmdPulsante_6.Image");
this._cmdPulsante_6.TabIndex = 8;
this._cmdPulsante_6.BackColor = System.Drawing.SystemColors.Control;
this._cmdPulsante_6.CausesValidation = true;
this._cmdPulsante_6.Enabled = true;
this._cmdPulsante_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdPulsante_6.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdPulsante_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdPulsante_6.TabStop = true;
this._cmdPulsante_6.Name = "_cmdPulsante_6";
this._Frame1_2.Text = "Output";
this._Frame1_2.Size = new System.Drawing.Size(193, 81);
this._Frame1_2.Location = new System.Drawing.Point(504, 296);
this._Frame1_2.TabIndex = 5;
this._Frame1_2.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_2.Enabled = true;
this._Frame1_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_2.Visible = true;
this._Frame1_2.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_2.Name = "_Frame1_2";
this._cmdPulsante_4.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this._cmdPulsante_4.Text = "&Exit";
this._cmdPulsante_4.Size = new System.Drawing.Size(177, 57);
this._cmdPulsante_4.Location = new System.Drawing.Point(8, 16);
this._cmdPulsante_4.Image = (System.Drawing.Image)resources.GetObject("_cmdPulsante_4.Image");
this._cmdPulsante_4.TabIndex = 6;
this._cmdPulsante_4.BackColor = System.Drawing.SystemColors.Control;
this._cmdPulsante_4.CausesValidation = true;
this._cmdPulsante_4.Enabled = true;
this._cmdPulsante_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdPulsante_4.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdPulsante_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdPulsante_4.TabStop = true;
this._cmdPulsante_4.Name = "_cmdPulsante_4";
this._Frame1_1.Size = new System.Drawing.Size(561, 81);
this._Frame1_1.Location = new System.Drawing.Point(472, 368);
this._Frame1_1.TabIndex = 0;
this._Frame1_1.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_1.Enabled = true;
this._Frame1_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_1.Visible = true;
this._Frame1_1.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_1.Name = "_Frame1_1";
this._cmdPulsante_3.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this._cmdPulsante_3.Text = "&Automatic";
this._cmdPulsante_3.Size = new System.Drawing.Size(137, 57);
this._cmdPulsante_3.Location = new System.Drawing.Point(416, 16);
this._cmdPulsante_3.Image = (System.Drawing.Image)resources.GetObject("_cmdPulsante_3.Image");
this._cmdPulsante_3.TabIndex = 4;
this._cmdPulsante_3.BackColor = System.Drawing.SystemColors.Control;
this._cmdPulsante_3.CausesValidation = true;
this._cmdPulsante_3.Enabled = true;
this._cmdPulsante_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdPulsante_3.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdPulsante_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdPulsante_3.TabStop = true;
this._cmdPulsante_3.Name = "_cmdPulsante_3";
this._cmdPulsante_2.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this._cmdPulsante_2.Text = "&Setup";
this._cmdPulsante_2.Size = new System.Drawing.Size(137, 57);
this._cmdPulsante_2.Location = new System.Drawing.Point(272, 16);
this._cmdPulsante_2.Image = (System.Drawing.Image)resources.GetObject("_cmdPulsante_2.Image");
this._cmdPulsante_2.TabIndex = 3;
this._cmdPulsante_2.BackColor = System.Drawing.SystemColors.Control;
this._cmdPulsante_2.CausesValidation = true;
this._cmdPulsante_2.Enabled = true;
this._cmdPulsante_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdPulsante_2.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdPulsante_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdPulsante_2.TabStop = true;
this._cmdPulsante_2.Name = "_cmdPulsante_2";
this._cmdPulsante_1.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this._cmdPulsante_1.Text = "&Disconnect";
this._cmdPulsante_1.Size = new System.Drawing.Size(113, 57);
this._cmdPulsante_1.Location = new System.Drawing.Point(152, 16);
this._cmdPulsante_1.Image = (System.Drawing.Image)resources.GetObject("_cmdPulsante_1.Image");
this._cmdPulsante_1.TabIndex = 2;
this._cmdPulsante_1.BackColor = System.Drawing.SystemColors.Control;
this._cmdPulsante_1.CausesValidation = true;
this._cmdPulsante_1.Enabled = true;
this._cmdPulsante_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdPulsante_1.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdPulsante_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdPulsante_1.TabStop = true;
this._cmdPulsante_1.Name = "_cmdPulsante_1";
this._cmdPulsante_0.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this._cmdPulsante_0.Text = "&Connect";
this._cmdPulsante_0.Size = new System.Drawing.Size(137, 57);
this._cmdPulsante_0.Location = new System.Drawing.Point(8, 16);
this._cmdPulsante_0.Image = (System.Drawing.Image)resources.GetObject("_cmdPulsante_0.Image");
this._cmdPulsante_0.TabIndex = 1;
this._cmdPulsante_0.BackColor = System.Drawing.SystemColors.Control;
this._cmdPulsante_0.CausesValidation = true;
this._cmdPulsante_0.Enabled = true;
this._cmdPulsante_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdPulsante_0.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdPulsante_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdPulsante_0.TabStop = true;
this._cmdPulsante_0.Name = "_cmdPulsante_0";
this.lbl8.Text = "server path";
this.lbl8.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl8.Size = new System.Drawing.Size(64, 14);
this.lbl8.Location = new System.Drawing.Point(8, 264);
this.lbl8.TabIndex = 17;
this.lbl8.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lbl8.BackColor = System.Drawing.Color.Transparent;
this.lbl8.Enabled = true;
this.lbl8.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl8.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl8.UseMnemonic = true;
this.lbl8.Visible = true;
this.lbl8.AutoSize = true;
this.lbl8.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl8.Name = "lbl8";
this.lbl11.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl11.Text = "DONE";
this.lbl11.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl11.ForeColor = System.Drawing.Color.FromArgb(0, 0, 192);
this.lbl11.Size = new System.Drawing.Size(36, 13);
this.lbl11.Location = new System.Drawing.Point(320, 80);
this.lbl11.TabIndex = 27;
this.lbl11.BackColor = System.Drawing.Color.Transparent;
this.lbl11.Enabled = true;
this.lbl11.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl11.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl11.UseMnemonic = true;
this.lbl11.Visible = true;
this.lbl11.AutoSize = true;
this.lbl11.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl11.Name = "lbl11";
this.lbl55.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl55.Text = "DONE";
this.lbl55.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl55.ForeColor = System.Drawing.Color.FromArgb(0, 0, 192);
this.lbl55.Size = new System.Drawing.Size(36, 13);
this.lbl55.Location = new System.Drawing.Point(320, 205);
this.lbl55.TabIndex = 26;
this.lbl55.BackColor = System.Drawing.Color.Transparent;
this.lbl55.Enabled = true;
this.lbl55.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl55.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl55.UseMnemonic = true;
this.lbl55.Visible = true;
this.lbl55.AutoSize = true;
this.lbl55.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl55.Name = "lbl55";
this.lbl5.Text = "&5. Copying files to 4POS Server";
this.lbl5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl5.Size = new System.Drawing.Size(169, 14);
this.lbl5.Location = new System.Drawing.Point(8, 205);
this.lbl5.TabIndex = 25;
this.lbl5.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lbl5.BackColor = System.Drawing.Color.Transparent;
this.lbl5.Enabled = true;
this.lbl5.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl5.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl5.UseMnemonic = true;
this.lbl5.Visible = true;
this.lbl5.AutoSize = true;
this.lbl5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl5.Name = "lbl5";
this.lbl44.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl44.Text = "DONE";
this.lbl44.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl44.ForeColor = System.Drawing.Color.FromArgb(0, 0, 192);
this.lbl44.Size = new System.Drawing.Size(36, 13);
this.lbl44.Location = new System.Drawing.Point(320, 173);
this.lbl44.TabIndex = 24;
this.lbl44.BackColor = System.Drawing.Color.Transparent;
this.lbl44.Enabled = true;
this.lbl44.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl44.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl44.UseMnemonic = true;
this.lbl44.Visible = true;
this.lbl44.AutoSize = true;
this.lbl44.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl44.Name = "lbl44";
this.lbl4.Text = "&4. Downloading";
this.lbl4.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl4.Size = new System.Drawing.Size(83, 14);
this.lbl4.Location = new System.Drawing.Point(8, 173);
this.lbl4.TabIndex = 23;
this.lbl4.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lbl4.BackColor = System.Drawing.Color.Transparent;
this.lbl4.Enabled = true;
this.lbl4.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl4.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl4.UseMnemonic = true;
this.lbl4.Visible = true;
this.lbl4.AutoSize = true;
this.lbl4.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl4.Name = "lbl4";
this.lbl33.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl33.Text = "DONE";
this.lbl33.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl33.ForeColor = System.Drawing.Color.FromArgb(0, 0, 192);
this.lbl33.Size = new System.Drawing.Size(36, 13);
this.lbl33.Location = new System.Drawing.Point(320, 141);
this.lbl33.TabIndex = 22;
this.lbl33.BackColor = System.Drawing.Color.Transparent;
this.lbl33.Enabled = true;
this.lbl33.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl33.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl33.UseMnemonic = true;
this.lbl33.Visible = true;
this.lbl33.AutoSize = true;
this.lbl33.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl33.Name = "lbl33";
this.lbl3.Text = "&3. Uploading ";
this.lbl3.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl3.Size = new System.Drawing.Size(69, 14);
this.lbl3.Location = new System.Drawing.Point(8, 141);
this.lbl3.TabIndex = 21;
this.lbl3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lbl3.BackColor = System.Drawing.Color.Transparent;
this.lbl3.Enabled = true;
this.lbl3.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl3.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl3.UseMnemonic = true;
this.lbl3.Visible = true;
this.lbl3.AutoSize = true;
this.lbl3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl3.Name = "lbl3";
this.lbl22.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl22.Text = "DONE";
this.lbl22.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl22.ForeColor = System.Drawing.Color.FromArgb(0, 0, 192);
this.lbl22.Size = new System.Drawing.Size(36, 13);
this.lbl22.Location = new System.Drawing.Point(320, 109);
this.lbl22.TabIndex = 20;
this.lbl22.BackColor = System.Drawing.Color.Transparent;
this.lbl22.Enabled = true;
this.lbl22.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl22.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl22.UseMnemonic = true;
this.lbl22.Visible = true;
this.lbl22.AutoSize = true;
this.lbl22.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl22.Name = "lbl22";
this.lbl2.Text = "&2. Connecting to File transfer engine";
this.lbl2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl2.Size = new System.Drawing.Size(200, 14);
this.lbl2.Location = new System.Drawing.Point(8, 109);
this.lbl2.TabIndex = 19;
this.lbl2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lbl2.BackColor = System.Drawing.Color.Transparent;
this.lbl2.Enabled = true;
this.lbl2.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl2.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl2.UseMnemonic = true;
this.lbl2.Visible = true;
this.lbl2.AutoSize = true;
this.lbl2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl2.Name = "lbl2";
this.lbl1.Text = "&1. Checking Internet connection";
this.lbl1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl1.Size = new System.Drawing.Size(175, 14);
this.lbl1.Location = new System.Drawing.Point(8, 80);
this.lbl1.TabIndex = 18;
this.lbl1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lbl1.BackColor = System.Drawing.Color.Transparent;
this.lbl1.Enabled = true;
this.lbl1.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl1.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl1.UseMnemonic = true;
this.lbl1.Visible = true;
this.lbl1.AutoSize = true;
this.lbl1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl1.Name = "lbl1";
this.lbl66.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl66.Text = "DONE";
this.lbl66.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl66.ForeColor = System.Drawing.Color.FromArgb(0, 0, 192);
this.lbl66.Size = new System.Drawing.Size(36, 13);
this.lbl66.Location = new System.Drawing.Point(320, 232);
this.lbl66.TabIndex = 16;
this.lbl66.BackColor = System.Drawing.Color.Transparent;
this.lbl66.Enabled = true;
this.lbl66.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl66.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl66.UseMnemonic = true;
this.lbl66.Visible = true;
this.lbl66.AutoSize = true;
this.lbl66.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl66.Name = "lbl66";
this.lbl6.Text = "&6. Closing Connection";
this.lbl6.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lbl6.Size = new System.Drawing.Size(120, 14);
this.lbl6.Location = new System.Drawing.Point(8, 232);
this.lbl6.TabIndex = 15;
this.lbl6.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lbl6.BackColor = System.Drawing.Color.Transparent;
this.lbl6.Enabled = true;
this.lbl6.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl6.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl6.UseMnemonic = true;
this.lbl6.Visible = true;
this.lbl6.AutoSize = true;
this.lbl6.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl6.Name = "lbl6";
this.Controls.Add(Command3);
this.Controls.Add(picOuter);
this.Controls.Add(cmdBookIN);
this.Controls.Add(cmdBookOut);
this.Controls.Add(cmdUpReport);
this.Controls.Add(txtPrevOrder);
this.Controls.Add(Command1);
this.Controls.Add(cmdExit);
this.Controls.Add(Picture1);
this.Controls.Add(Text4);
this.Controls.Add(Text3);
this.Controls.Add(Text2);
this.Controls.Add(_cmdPulsante_5);
this.Controls.Add(picButtons);
this.Controls.Add(_Frame1_0);
this.Controls.Add(_Frame1_3);
this.Controls.Add(_Frame1_2);
this.Controls.Add(_Frame1_1);
this.Controls.Add(lbl8);
this.Controls.Add(lbl11);
this.Controls.Add(lbl55);
this.Controls.Add(lbl5);
this.Controls.Add(lbl44);
this.Controls.Add(lbl4);
this.Controls.Add(lbl33);
this.Controls.Add(lbl3);
this.Controls.Add(lbl22);
this.Controls.Add(lbl2);
this.Controls.Add(lbl1);
this.Controls.Add(lbl66);
this.Controls.Add(lbl6);
this.picOuter.Controls.Add(picInner);
this.Picture1.Controls.Add(cmdToday);
this.Picture1.Controls.Add(_DTPicker1_0);
this.Picture1.Controls.Add(_DTPicker1_1);
this.Picture1.Controls.Add(_lbl_0);
this.picButtons.Controls.Add(cmdClearLock);
this.picButtons.Controls.Add(cmdClose);
this.picButtons.Controls.Add(Command2);
this.picButtons.Controls.Add(cmdCheckWOrder);
this._Frame1_0.Controls.Add(Text1);
this._Frame1_0.Controls.Add(_Label1_1);
this._Frame1_3.Controls.Add(_cmdPulsante_7);
this._Frame1_3.Controls.Add(_cmdPulsante_6);
this._Frame1_2.Controls.Add(_cmdPulsante_4);
this._Frame1_1.Controls.Add(_cmdPulsante_3);
this._Frame1_1.Controls.Add(_cmdPulsante_2);
this._Frame1_1.Controls.Add(_cmdPulsante_1);
this._Frame1_1.Controls.Add(_cmdPulsante_0);
//Me.DTPicker1.SetIndex(_DTPicker1_0, CType(0, Short))
//Me.DTPicker1.SetIndex(_DTPicker1_1, CType(1, Short))
//Me.Frame1.SetIndex(_Frame1_0, CType(0, Short))
//Me.Frame1.SetIndex(_Frame1_3, CType(3, Short))
//Me.Frame1.SetIndex(_Frame1_2, CType(2, Short))
//Me.Frame1.SetIndex(_Frame1_1, CType(1, Short))
//Me.Label1.SetIndex(_Label1_1, CType(1, Short))
//Me.cmdPulsante.SetIndex(_cmdPulsante_5, CType(5, Short))
//Me.cmdPulsante.SetIndex(_cmdPulsante_7, CType(7, Short))
//Me.cmdPulsante.SetIndex(_cmdPulsante_6, CType(6, Short))
//Me.cmdPulsante.SetIndex(_cmdPulsante_4, CType(4, Short))
//Me.cmdPulsante.SetIndex(_cmdPulsante_3, CType(3, Short))
//Me.cmdPulsante.SetIndex(_cmdPulsante_2, CType(2, Short))
//Me.cmdPulsante.SetIndex(_cmdPulsante_1, CType(1, Short))
//Me.cmdPulsante.SetIndex(_cmdPulsante_0, CType(0, Short))
//Me.lbl.SetIndex(_lbl_0, CType(0, Short))
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.cmdPulsante, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.Label1, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.Frame1, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.DTPicker1, System.ComponentModel.ISupportInitialize).EndInit()
((System.ComponentModel.ISupportInitialize)this._DTPicker1_1).EndInit();
((System.ComponentModel.ISupportInitialize)this._DTPicker1_0).EndInit();
this.picOuter.ResumeLayout(false);
this.Picture1.ResumeLayout(false);
this.picButtons.ResumeLayout(false);
this._Frame1_0.ResumeLayout(false);
this._Frame1_3.ResumeLayout(false);
this._Frame1_2.ResumeLayout(false);
this._Frame1_1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.7.1. Information about active electronic warfare (EW) emissions and active EW countermeasures shall be communicated using an Electromagnetic Emission PDU. COMPLETE (I think)
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(EventID))]
[XmlInclude(typeof(ElectronicEmissionSystemData))]
public partial class ElectronicEmissionsPdu : DistributedEmissionsFamilyPdu, IEquatable<ElectronicEmissionsPdu>
{
/// <summary>
/// ID of the entity emitting
/// </summary>
private EntityID _emittingEntityID = new EntityID();
/// <summary>
/// ID of event
/// </summary>
private EventID _eventID = new EventID();
/// <summary>
/// This field shall be used to indicate if the data in the PDU represents a state update or just data that has changed since issuance of the last Electromagnetic Emission PDU [relative to the identified entity and emission system(s)].
/// </summary>
private byte _stateUpdateIndicator;
/// <summary>
/// This field shall specify the number of emission systems being described in the current PDU.
/// </summary>
private byte _numberOfSystems;
/// <summary>
/// padding
/// </summary>
private ushort _paddingForEmissionsPdu;
/// <summary>
/// Electronic emmissions systems
/// </summary>
private List<ElectronicEmissionSystemData> _systems = new List<ElectronicEmissionSystemData>();
/// <summary>
/// Initializes a new instance of the <see cref="ElectronicEmissionsPdu"/> class.
/// </summary>
public ElectronicEmissionsPdu()
{
PduType = (byte)23;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(ElectronicEmissionsPdu left, ElectronicEmissionsPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(ElectronicEmissionsPdu left, ElectronicEmissionsPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._emittingEntityID.GetMarshalledSize(); // this._emittingEntityID
marshalSize += this._eventID.GetMarshalledSize(); // this._eventID
marshalSize += 1; // this._stateUpdateIndicator
marshalSize += 1; // this._numberOfSystems
marshalSize += 2; // this._paddingForEmissionsPdu
for (int idx = 0; idx < this._systems.Count; idx++)
{
ElectronicEmissionSystemData listElement = (ElectronicEmissionSystemData)this._systems[idx];
marshalSize += listElement.GetMarshalledSize();
}
return marshalSize;
}
/// <summary>
/// Gets or sets the ID of the entity emitting
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "emittingEntityID")]
public EntityID EmittingEntityID
{
get
{
return this._emittingEntityID;
}
set
{
this._emittingEntityID = value;
}
}
/// <summary>
/// Gets or sets the ID of event
/// </summary>
[XmlElement(Type = typeof(EventID), ElementName = "eventID")]
public EventID EventID
{
get
{
return this._eventID;
}
set
{
this._eventID = value;
}
}
/// <summary>
/// Gets or sets the This field shall be used to indicate if the data in the PDU represents a state update or just data that has changed since issuance of the last Electromagnetic Emission PDU [relative to the identified entity and emission system(s)].
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "stateUpdateIndicator")]
public byte StateUpdateIndicator
{
get
{
return this._stateUpdateIndicator;
}
set
{
this._stateUpdateIndicator = value;
}
}
/// <summary>
/// Gets or sets the This field shall specify the number of emission systems being described in the current PDU.
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfSystems method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(byte), ElementName = "numberOfSystems")]
public byte NumberOfSystems
{
get
{
return this._numberOfSystems;
}
set
{
this._numberOfSystems = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "paddingForEmissionsPdu")]
public ushort PaddingForEmissionsPdu
{
get
{
return this._paddingForEmissionsPdu;
}
set
{
this._paddingForEmissionsPdu = value;
}
}
/// <summary>
/// Gets the Electronic emmissions systems
/// </summary>
[XmlElement(ElementName = "systemsList", Type = typeof(List<ElectronicEmissionSystemData>))]
public List<ElectronicEmissionSystemData> Systems
{
get
{
return this._systems;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._emittingEntityID.Marshal(dos);
this._eventID.Marshal(dos);
dos.WriteUnsignedByte((byte)this._stateUpdateIndicator);
dos.WriteUnsignedByte((byte)this._systems.Count);
dos.WriteUnsignedShort((ushort)this._paddingForEmissionsPdu);
for (int idx = 0; idx < this._systems.Count; idx++)
{
ElectronicEmissionSystemData aElectronicEmissionSystemData = (ElectronicEmissionSystemData)this._systems[idx];
aElectronicEmissionSystemData.Marshal(dos);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._emittingEntityID.Unmarshal(dis);
this._eventID.Unmarshal(dis);
this._stateUpdateIndicator = dis.ReadUnsignedByte();
this._numberOfSystems = dis.ReadUnsignedByte();
this._paddingForEmissionsPdu = dis.ReadUnsignedShort();
for (int idx = 0; idx < this.NumberOfSystems; idx++)
{
ElectronicEmissionSystemData anX = new ElectronicEmissionSystemData();
anX.Unmarshal(dis);
this._systems.Add(anX);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<ElectronicEmissionsPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<emittingEntityID>");
this._emittingEntityID.Reflection(sb);
sb.AppendLine("</emittingEntityID>");
sb.AppendLine("<eventID>");
this._eventID.Reflection(sb);
sb.AppendLine("</eventID>");
sb.AppendLine("<stateUpdateIndicator type=\"byte\">" + this._stateUpdateIndicator.ToString(CultureInfo.InvariantCulture) + "</stateUpdateIndicator>");
sb.AppendLine("<systems type=\"byte\">" + this._systems.Count.ToString(CultureInfo.InvariantCulture) + "</systems>");
sb.AppendLine("<paddingForEmissionsPdu type=\"ushort\">" + this._paddingForEmissionsPdu.ToString(CultureInfo.InvariantCulture) + "</paddingForEmissionsPdu>");
for (int idx = 0; idx < this._systems.Count; idx++)
{
sb.AppendLine("<systems" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"ElectronicEmissionSystemData\">");
ElectronicEmissionSystemData aElectronicEmissionSystemData = (ElectronicEmissionSystemData)this._systems[idx];
aElectronicEmissionSystemData.Reflection(sb);
sb.AppendLine("</systems" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</ElectronicEmissionsPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as ElectronicEmissionsPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(ElectronicEmissionsPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._emittingEntityID.Equals(obj._emittingEntityID))
{
ivarsEqual = false;
}
if (!this._eventID.Equals(obj._eventID))
{
ivarsEqual = false;
}
if (this._stateUpdateIndicator != obj._stateUpdateIndicator)
{
ivarsEqual = false;
}
if (this._numberOfSystems != obj._numberOfSystems)
{
ivarsEqual = false;
}
if (this._paddingForEmissionsPdu != obj._paddingForEmissionsPdu)
{
ivarsEqual = false;
}
if (this._systems.Count != obj._systems.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._systems.Count; idx++)
{
if (!this._systems[idx].Equals(obj._systems[idx]))
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._emittingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._eventID.GetHashCode();
result = GenerateHash(result) ^ this._stateUpdateIndicator.GetHashCode();
result = GenerateHash(result) ^ this._numberOfSystems.GetHashCode();
result = GenerateHash(result) ^ this._paddingForEmissionsPdu.GetHashCode();
if (this._systems.Count > 0)
{
for (int idx = 0; idx < this._systems.Count; idx++)
{
result = GenerateHash(result) ^ this._systems[idx].GetHashCode();
}
}
return result;
}
}
}
| |
// Python Tools for Visual Studio
// 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 ON AN *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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis.Values {
internal class ClassInfo : AnalysisValue, IReferenceableContainer {
private AnalysisUnit _analysisUnit;
private readonly List<IAnalysisSet> _bases;
internal Mro _mro;
private readonly InstanceInfo _instanceInfo;
private ClassScope _scope;
private readonly int _declVersion;
private VariableDef _metaclass;
private ReferenceDict _references;
private VariableDef _subclasses;
private IAnalysisSet _baseSpecialization;
private readonly PythonAnalyzer _projectState;
internal ClassInfo(ClassDefinition klass, AnalysisUnit outerUnit) {
_instanceInfo = new InstanceInfo(this);
_bases = new List<IAnalysisSet>();
_declVersion = outerUnit.ProjectEntry.AnalysisVersion;
_projectState = outerUnit.ProjectState;
_mro = new Mro(this);
}
public override AnalysisUnit AnalysisUnit {
get {
return _analysisUnit;
}
}
internal void SetAnalysisUnit(AnalysisUnit unit) {
Debug.Assert(_analysisUnit == null);
_analysisUnit = unit;
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
if (unit != null) {
return AddCall(node, keywordArgNames, unit, args);
}
return _instanceInfo.SelfSet;
}
private IAnalysisSet AddCall(Node node, NameExpression[] keywordArgNames, AnalysisUnit unit, IAnalysisSet[] args) {
var init = GetMemberNoReferences(node, unit, "__init__", false);
var initArgs = Utils.Concat(_instanceInfo.SelfSet, args);
foreach (var initFunc in init) {
initFunc.Call(node, unit, initArgs, keywordArgNames);
}
// TODO: If we checked for metaclass, we could pass it in as the cls arg here
var n = GetMemberNoReferences(node, unit, "__new__", false);
var newArgs = Utils.Concat(SelfSet, args);
var newResult = AnalysisSet.Empty;
bool anyCustom = false;
foreach (var newFunc in n) {
if (!(newFunc is BuiltinFunctionInfo)) {
anyCustom = true;
}
newResult = newResult.Union(newFunc.Call(node, unit, newArgs, keywordArgNames));
}
if (anyCustom) {
return newResult;
}
if (newResult.Count == 0 || newResult.All(ns => ns.IsOfType(unit.ProjectState.ClassInfos[BuiltinTypeId.Object]))) {
if (_baseSpecialization != null && _baseSpecialization.Count != 0) {
var specializedInstances = _baseSpecialization.Call(
node, unit, args, keywordArgNames
);
var res = (SpecializedInstanceInfo)unit.Scope.GetOrMakeNodeValue(
node,
NodeValueKind.SpecializedInstance,
(node_) => new SpecializedInstanceInfo(this, specializedInstances)
);
res._instances = specializedInstances;
return res;
}
return _instanceInfo.SelfSet;
}
return newResult;
}
public ClassDefinition ClassDefinition {
get { return _analysisUnit.Ast as ClassDefinition; }
}
public override string ShortDescription {
get {
return ClassDefinition.Name;
}
}
public override string Description {
get {
var res = "class " + ClassDefinition.Name;
if (!String.IsNullOrEmpty(Documentation)) {
res += Environment.NewLine + Documentation;
}
return res;
}
}
public override string Name {
get {
return ClassDefinition.Name;
}
}
public VariableDef SubClasses {
get {
if (_subclasses == null) {
_subclasses = new VariableDef();
}
return _subclasses;
}
}
public VariableDef MetaclassVariable {
get {
return _metaclass;
}
}
public VariableDef GetOrCreateMetaclassVariable() {
if (_metaclass == null) {
_metaclass = new VariableDef();
}
return _metaclass;
}
public override string Documentation {
get {
if (ClassDefinition.Body != null) {
return ClassDefinition.Body.Documentation.TrimDocumentation();
}
return "";
}
}
public override IEnumerable<LocationInfo> Locations {
get {
if (_declVersion == DeclaringModule.AnalysisVersion) {
var start = ClassDefinition.NameExpression.GetStart(ClassDefinition.GlobalParent);
var end = ClassDefinition.GetEnd(ClassDefinition.GlobalParent);
return new[] { new LocationInfo(DeclaringModule.FilePath, start.Line, start.Column, end.Line, end.Column) };
}
return LocationInfo.Empty;
}
}
internal override BuiltinTypeId TypeId {
get {
return BuiltinTypeId.Type;
}
}
public override IPythonType PythonType {
get {
return _projectState.Types[BuiltinTypeId.Type];
}
}
internal override bool IsOfType(IAnalysisSet klass) {
return klass.Contains(_projectState.ClassInfos[BuiltinTypeId.Type]);
}
public override IPythonProjectEntry DeclaringModule {
get {
return _analysisUnit.ProjectEntry;
}
}
public override int DeclaringVersion {
get {
return _declVersion;
}
}
public override IEnumerable<OverloadResult> Overloads {
get {
var result = new List<OverloadResult>();
VariableDef init;
if (Scope.TryGetVariable("__init__", out init)) {
// this type overrides __init__, display that for it's help
foreach (var initFunc in init.TypesNoCopy) {
foreach (var overload in initFunc.Overloads) {
result.Add(GetInitOverloadResult(overload));
}
}
}
VariableDef @new;
if (Scope.TryGetVariable("__new__", out @new)) {
foreach (var newFunc in @new.TypesNoCopy) {
foreach (var overload in newFunc.Overloads) {
result.Add(GetNewOverloadResult(overload));
}
}
}
if (result.Count == 0) {
foreach (var baseClass in _bases) {
foreach (var ns in baseClass) {
if (ns.TypeId == BuiltinTypeId.Object) {
continue;
}
if (ns.Push()) {
try {
foreach (var overload in ns.Overloads) {
result.Add(
new SimpleOverloadResult(
overload.Parameters,
ClassDefinition.Name,
overload.Documentation
)
);
}
} finally {
ns.Pop();
}
}
}
}
}
if (result.Count == 0) {
// Old style class?
result.Add(new SimpleOverloadResult(new ParameterResult[0], ClassDefinition.Name, ClassDefinition.Body.Documentation.TrimDocumentation()));
}
// TODO: Filter out duplicates?
return result;
}
}
private SimpleOverloadResult GetNewOverloadResult(OverloadResult overload) {
var doc = overload.Documentation;
return new SimpleOverloadResult(
overload.Parameters.RemoveFirst(),
ClassDefinition.Name,
String.IsNullOrEmpty(doc) ? Documentation : doc
);
}
private SimpleOverloadResult GetInitOverloadResult(OverloadResult overload) {
var doc = overload.Documentation;
return new SimpleOverloadResult(
overload.Parameters.RemoveFirst(),
ClassDefinition.Name,
String.IsNullOrEmpty(doc) ? Documentation : doc
);
}
public IEnumerable<IAnalysisSet> Bases {
get {
return _bases;
}
}
public override IEnumerable<IAnalysisSet> Mro {
get {
return _mro;
}
}
public void SetBases(IEnumerable<IAnalysisSet> bases) {
_bases.Clear();
_bases.AddRange(bases);
_mro.Recompute();
RecomputeBaseSpecialization();
}
private void RecomputeBaseSpecialization() {
IAnalysisSet builtinClassSet = AnalysisSet.Empty;
foreach (var classInfo in _mro) {
BuiltinClassInfo builtin = classInfo as BuiltinClassInfo;
if (builtin != null && builtin.TypeId != BuiltinTypeId.Object) {
var builtinType = _projectState.GetBuiltinType(builtin.PythonType);
if (builtinType.GetType() != typeof(BuiltinClassInfo)) {
// we have a specialized built-in class, we want its behavior too...
builtinClassSet = builtinClassSet.Union(builtinType.SelfSet, true);
}
}
}
_baseSpecialization = builtinClassSet;
}
public void SetBase(int index, IAnalysisSet baseSet) {
while (index >= _bases.Count) {
_bases.Add(AnalysisSet.Empty);
}
_bases[index] = baseSet;
_mro.Recompute();
RecomputeBaseSpecialization();
}
public InstanceInfo Instance {
get {
return _instanceInfo;
}
}
public override IAnalysisSet GetInstanceType() {
return Instance;
}
/// <summary>
/// Gets all members of this class that are not inherited from its base classes.
/// </summary>
public IDictionary<string, IAnalysisSet> GetAllImmediateMembers(IModuleContext moduleContext, GetMemberOptions options) {
var result = new Dictionary<string, IAnalysisSet>(Scope.VariableCount);
foreach (var v in Scope.AllVariables) {
v.Value.ClearOldValues();
if (v.Value.VariableStillExists) {
result[v.Key] = v.Value.Types;
}
}
if (!options.HasFlag(GetMemberOptions.DeclaredOnly)) {
if (!result.ContainsKey("__doc__")) {
result["__doc__"] = GetObjectMember(moduleContext, "__doc__");
}
if (!result.ContainsKey("__class__")) {
result["__class__"] = GetObjectMember(moduleContext, "__class__");
}
}
return result;
}
public override IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext, GetMemberOptions options = GetMemberOptions.None) {
IDictionary<string, IAnalysisSet> result;
if (options.HasFlag(GetMemberOptions.DeclaredOnly)) {
result = GetAllImmediateMembers(moduleContext, options);
} else {
result = _mro.GetAllMembers(moduleContext, options);
}
if (_metaclass != null) {
foreach (var type in _metaclass.Types) {
if (type.Push()) {
try {
foreach (var nameValue in type.GetAllMembers(moduleContext)) {
result[nameValue.Key] = nameValue.Value.GetDescriptor(null, this, type, Instance.ProjectState._evalUnit);
}
} finally {
type.Pop();
}
}
}
}
return result;
}
private AnalysisValue GetObjectMember(IModuleContext moduleContext, string name) {
return _analysisUnit.ProjectState.GetAnalysisValueFromObjects(_analysisUnit.ProjectState.Types[BuiltinTypeId.Object].GetMember(moduleContext, name));
}
internal override void AddReference(Node node, AnalysisUnit unit) {
if (!unit.ForEval) {
if (_references == null) {
_references = new ReferenceDict();
}
_references.GetReferences(unit.DeclaringModule.ProjectEntry).AddReference(new EncodedLocation(unit, node));
}
}
public override IAnalysisSet GetTypeMember(Node node, AnalysisUnit unit, string name) {
return GetMemberNoReferences(node, unit, name).GetDescriptor(node, unit.ProjectState._noneInst, this, unit);
}
/// <summary>
/// Get the member of this class by name that is not inherited from one of its base classes.
/// </summary>
public IAnalysisSet GetImmediateMemberNoReferences(Node node, AnalysisUnit unit, string name, bool addRef = true) {
var result = AnalysisSet.Empty;
var v = Scope.GetVariable(node, unit, name, addRef);
if (v != null) {
result = v.Types;
}
return result;
}
public IAnalysisSet GetMemberNoReferences(Node node, AnalysisUnit unit, string name, bool addRef = true) {
var result = _mro.GetMemberNoReferences(node, unit, name, addRef);
if (result != null && result.Count > 0) {
return result;
}
if (_metaclass != null) {
foreach (var type in _metaclass.Types) {
if (type.Push()) {
try {
foreach (var metaValue in type.GetMember(node, unit, name)) {
foreach (var boundValue in metaValue.GetDescriptor(node, this, type, unit)) {
result = result.Union(boundValue);
}
}
} finally {
type.Pop();
}
}
}
if (result != null && result.Count > 0) {
return result;
}
}
return GetOldStyleMember(name, unit.DeclaringModule.InterpreterContext);
}
private IAnalysisSet GetOldStyleMember(string name, IModuleContext context) {
switch (name) {
case "__doc__":
case "__class__":
return GetObjectMember(context, name).SelfSet;
}
return AnalysisSet.Empty;
}
public override void SetMember(Node node, AnalysisUnit unit, string name, IAnalysisSet value) {
var variable = Scope.CreateVariable(node, unit, name, false);
variable.AddAssignment(node, unit);
variable.AddTypes(unit, value);
}
public override void DeleteMember(Node node, AnalysisUnit unit, string name) {
var v = Scope.GetVariable(node, unit, name);
if (v != null) {
v.AddReference(node, unit);
}
}
public override PythonMemberType MemberType {
get {
return PythonMemberType.Class;
}
}
public override string ToString() {
return "user class " + _analysisUnit.FullName + " (" + _declVersion + ")";
}
public ClassScope Scope {
get { return _scope; }
set {
// Scope should only be set once
Debug.Assert(_scope == null);
_scope = value;
}
}
/// <summary>
/// Provides a stable ordering of class definitions that is used solely
/// to ensure that unioning two classes is symmetrical.
///
/// Otherwise, classes C and D would be merged asymmetrically:
///
/// class A: pass
/// class B: pass
/// class C(A, B): pass
/// class D(B, A): pass
/// </summary>
/// <remarks>
/// This does not have to be 100% reliable in order to avoid breaking
/// the analysis (except when FULL_VALIDATION is active). It is also
/// called very often, so there is more to be lost by making it robust
/// and slow.
///
/// The current implementation will break only when two classes are
/// defined with the same name at the same character index in two
/// different files and with problematic MROs.
/// </remarks>
private static bool IsFirstForMroUnion(ClassDefinition cd1, ClassDefinition cd2) {
if (cd1.StartIndex != cd2.StartIndex) {
return cd1.StartIndex > cd2.StartIndex;
}
return cd1.NameExpression.Name.CompareTo(cd2.NameExpression.Name) > 0;
}
internal override AnalysisValue UnionMergeTypes(AnalysisValue ns, int strength) {
if (strength >= MergeStrength.ToObject) {
return _projectState.ClassInfos[BuiltinTypeId.Type];
} else if (strength >= MergeStrength.ToBaseClass) {
var ci = ns as ClassInfo;
if (ci != null) {
IEnumerable<AnalysisValue> mro1;
AnalysisValue[] mro2;
if (IsFirstForMroUnion(ClassDefinition, ci.ClassDefinition)) {
mro1 = Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable());
mro2 = ci.Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable()).ToArray();
} else {
mro1 = ci.Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable());
mro2 = Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable()).ToArray();
}
return mro1.FirstOrDefault(cls => mro2.Contains(cls)) ?? _projectState.ClassInfos[BuiltinTypeId.Object];
}
var bci = ns as BuiltinClassInfo;
if (bci != null) {
return bci;
}
}
return base.UnionMergeTypes(ns, strength);
}
internal override bool UnionEquals(AnalysisValue ns, int strength) {
if (strength >= MergeStrength.ToObject) {
var type = _projectState.ClassInfos[BuiltinTypeId.Type];
return ns is ClassInfo || ns is BuiltinClassInfo || ns == type || ns == type.Instance;
} else if (strength >= MergeStrength.ToBaseClass) {
var ci = ns as ClassInfo;
if (ci != null) {
IEnumerable<AnalysisValue> mro1;
AnalysisValue[] mro2;
if (IsFirstForMroUnion(ClassDefinition, ci.ClassDefinition)) {
mro1 = Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable());
mro2 = ci.Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable()).ToArray();
} else {
mro1 = ci.Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable());
mro2 = Mro.SelectMany().Except(_projectState.DoNotUnionInMro.AsEnumerable()).ToArray();
}
return mro1.Any(cls => mro2.Contains(cls));
}
var bci = ns as BuiltinClassInfo;
if (bci != null &&
!_projectState.DoNotUnionInMro.Contains(this) &&
!_projectState.DoNotUnionInMro.Contains(bci)) {
return Mro.Any(m => m.Contains(bci));
}
}
return base.UnionEquals(ns, strength);
}
internal override int UnionHashCode(int strength) {
if (strength >= MergeStrength.ToBaseClass) {
return _projectState.ClassInfos[BuiltinTypeId.Type].GetHashCode();
}
return base.UnionHashCode(strength);
}
#region IVariableDefContainer Members
public IEnumerable<IReferenceable> GetDefinitions(string name) {
var result = new List<IReferenceable>();
VariableDef def;
if (_scope.TryGetVariable(name, out def)) {
result.Add(def);
}
if (Push()) {
try {
result.AddRange(Bases.SelectMany(b => GetDefinitions(name, b)));
result.AddRange(GetDefinitions(name, SubClasses.TypesNoCopy));
} finally {
Pop();
}
}
return result;
}
private IEnumerable<IReferenceable> GetDefinitions(string name, IEnumerable<AnalysisValue> nses) {
var result = new List<IReferenceable>();
foreach (var subType in nses) {
if (subType.Push()) {
IReferenceableContainer container = subType as IReferenceableContainer;
if (container != null) {
result.AddRange(container.GetDefinitions(name));
}
subType.Pop();
}
}
return result;
}
#endregion
#region IReferenceable Members
internal override IEnumerable<LocationInfo> References {
get {
if (_references != null) {
return _references.AllReferences;
}
return new LocationInfo[0];
}
}
#endregion
}
/// <summary>
/// Represents the method resolution order of a Python class according to C3 rules.
/// </summary>
/// <remarks>
/// The rules are described in detail at http://www.python.org/download/releases/2.3/mro/
/// </remarks>
internal class Mro : DependentData, IEnumerable<IAnalysisSet> {
private readonly ClassInfo _classInfo;
private List<AnalysisValue> _mroList;
private bool _isValid = true;
public Mro(ClassInfo classInfo) {
_classInfo = classInfo;
_mroList = new List<AnalysisValue> { classInfo };
}
public bool IsValid {
get { return _isValid; }
}
public IEnumerator<IAnalysisSet> GetEnumerator() {
return _mroList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public void Recompute() {
var mroList = new List<AnalysisValue> { _classInfo };
var isValid = true;
var bases = _classInfo.Bases;
if (bases.Any()) {
var mergeList = new List<List<AnalysisValue>>();
var finalMro = new List<AnalysisValue>();
foreach (var baseClass in bases.SelectMany()) {
var klass = baseClass as ClassInfo;
var builtInClass = baseClass as BuiltinClassInfo;
if (klass != null && klass.Push()) {
try {
if (!klass._mro.IsValid) {
isValid = false;
break;
}
finalMro.Add(klass);
mergeList.Add(klass.Mro.SelectMany().ToList());
} finally {
klass.Pop();
}
} else if (builtInClass != null && builtInClass.Push()) {
try {
finalMro.Add(builtInClass);
mergeList.Add(builtInClass.Mro.SelectMany().ToList());
} finally {
builtInClass.Pop();
}
}
}
if (isValid) {
mergeList.Add(finalMro);
mergeList.RemoveAll(mro => mro.Count == 0);
while (mergeList.Count > 0) {
AnalysisValue nextInMro = null;
for (int i = 0; i < mergeList.Count; ++i) {
// Select candidate head
var candidate = mergeList[i][0];
// Look for the candidate in the tails of every other MRO
if (!mergeList.Any(baseMro => baseMro.Skip(1).Contains(candidate))) {
// Candidate is good, so stop searching.
nextInMro = candidate;
break;
}
}
// No valid MRO for this class
if (nextInMro == null) {
isValid = false;
break;
}
mroList.Add(nextInMro);
// Remove all instances of that class from potentially being returned again
foreach (var mro in mergeList) {
mro.RemoveAll(ns => ns == nextInMro);
}
// Remove all lists that are now empty.
mergeList.RemoveAll(mro => mro.Count == 0);
}
}
}
// If the MRO is invalid, we only want the class itself to be there so that we
// will show all members defined in it, but nothing else.
if (!isValid) {
mroList.Clear();
mroList.Add(_classInfo);
}
if (_isValid != isValid || !_mroList.SequenceEqual(mroList)) {
_isValid = isValid;
_mroList = mroList;
EnqueueDependents();
}
}
public IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext, GetMemberOptions options) {
return GetAllMembersOfMro(this, moduleContext, options);
}
/// <summary>
/// Compute a list of all members, given the MRO list of types, and taking override rules into account.
/// </summary>
public static IDictionary<string, IAnalysisSet> GetAllMembersOfMro(IEnumerable<IAnalysisSet> mro, IModuleContext moduleContext, GetMemberOptions options) {
var result = new Dictionary<string, IAnalysisSet>();
// MRO is a list of namespaces corresponding to classes, but each entry can be a union of several different classes.
// Therefore, within a single entry, we want to make a union of members from each; but between entries, we
// want the first entry in MRO to suppress any members with the same names from the following entries.
foreach (var entry in mro) {
var entryMembers = new Dictionary<string, IAnalysisSet>();
foreach (var ns in entry) {
// If it's another non-builtin class, we don't want its inherited members, since we'll account
// for them while processing our own MRO - we only want its immediate members.
var classInfo = ns as ClassInfo;
var classMembers = classInfo != null ? classInfo.GetAllImmediateMembers(moduleContext, options) : ns.GetAllMembers(moduleContext);
foreach (var kvp in classMembers) {
IAnalysisSet existing;
if (!entryMembers.TryGetValue(kvp.Key, out existing)) {
entryMembers[kvp.Key] = kvp.Value;
} else {
entryMembers[kvp.Key] = existing.Union(kvp.Value);
}
}
}
foreach (var member in entryMembers) {
if (!result.ContainsKey(member.Key)) {
result.Add(member.Key, member.Value);
}
}
}
return result;
}
public IAnalysisSet GetMemberNoReferences(Node node, AnalysisUnit unit, string name, bool addRef = true) {
return GetMemberFromMroNoReferences(this, node, unit, name, addRef);
}
/// <summary>
/// Get the member by name, given the MRO list, and taking override rules into account.
/// </summary>
public static IAnalysisSet GetMemberFromMroNoReferences(IEnumerable<IAnalysisSet> mro, Node node, AnalysisUnit unit, string name, bool addRef = true) {
if (mro == null) {
return AnalysisSet.Empty;
}
// Union all members within a single MRO entry, but stop at the first entry that yields a non-empty set since it overrides any that follow.
var result = AnalysisSet.Empty;
foreach (var mroEntry in mro) {
foreach (var ns in mroEntry) {
var classInfo = ns as ClassInfo;
if (classInfo != null) {
var v = classInfo.Scope.GetVariable(node, unit, name, addRef);
if (v != null) {
result = result.Union(v.Types);
}
} else {
result = result.Union(ns.GetMember(node, unit, name));
}
}
if (result != null && result.Count > 0) {
break;
}
}
return result;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
namespace Microsoft.AzureStack.Management
{
public static partial class ManagedSubscriptionOperationsExtensions
{
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='parameters'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedSubscriptionCreateOrUpdateResult CreateOrUpdate(this IManagedSubscriptionOperations operations, ManagedSubscriptionCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedSubscriptionOperations)s).CreateOrUpdateAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='parameters'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedSubscriptionCreateOrUpdateResult> CreateOrUpdateAsync(this IManagedSubscriptionOperations operations, ManagedSubscriptionCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='subscriptionId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IManagedSubscriptionOperations operations, string subscriptionId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedSubscriptionOperations)s).DeleteAsync(subscriptionId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='subscriptionId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IManagedSubscriptionOperations operations, string subscriptionId)
{
return operations.DeleteAsync(subscriptionId, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='subscriptionId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedSubscriptionGetResult Get(this IManagedSubscriptionOperations operations, string subscriptionId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedSubscriptionOperations)s).GetAsync(subscriptionId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='subscriptionId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedSubscriptionGetResult> GetAsync(this IManagedSubscriptionOperations operations, string subscriptionId)
{
return operations.GetAsync(subscriptionId, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='includeDetails'>
/// Required.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedSubscriptionListResult List(this IManagedSubscriptionOperations operations, bool includeDetails)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedSubscriptionOperations)s).ListAsync(includeDetails);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='includeDetails'>
/// Required.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedSubscriptionListResult> ListAsync(this IManagedSubscriptionOperations operations, bool includeDetails)
{
return operations.ListAsync(includeDetails, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='nextLink'>
/// Required. Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedSubscriptionListResult ListNext(this IManagedSubscriptionOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedSubscriptionOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedSubscriptionOperations.
/// </param>
/// <param name='nextLink'>
/// Required. Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedSubscriptionListResult> ListNextAsync(this IManagedSubscriptionOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
namespace Comzept.Library.Drawing.ImageInfo
{
///<summary>
///Unit of measure used for the horizontal resolution and the vertical resolution.
///</summary>
public enum ResolutionUnit: ushort
{
///<summary>Dots Per Inch</summary>
dpi = 2,
///<summary>Centimeters Per Inch</summary>
dpcm =3
}
///<summary>
///Image orientation viewed in terms of rows and columns.
///</summary>
public enum Orientation: ushort
{
///<summary>The 0th row is at the top of the visual image, and the 0th column is the visual left side.</summary>
TopLeft = 1,
///<summary>The 0th row is at the visual top of the image, and the 0th column is the visual right side.</summary>
TopRight = 2,
///<summary>The 0th row is at the visual bottom of the image, and the 0th column is the visual right side.</summary>
BottomLeft = 3,
///<summary>The 0th row is at the visual bottom of the image, and the 0th column is the visual right side.</summary>
BottomRight = 4,
///<summary>The 0th row is the visual left side of the image, and the 0th column is the visual top.</summary>
LeftTop = 5,
///<summary>The 0th row is the visual right side of the image, and the 0th column is the visual top.</summary>
RightTop = 6,
///<summary>The 0th row is the visual right side of the image, and the 0th column is the visual bottom.</summary>
RightBottom = 7,
///<summary>The 0th row is the visual left side of the image, and the 0th column is the visual bottom.</summary>
LeftBottom = 8
}
///<summary>
/// Class of the program used by the camera to set exposure when the picture is taken.
///</summary>
public enum ExposureProg: ushort
{
///<summary>not defined</summary>
Undefined = 0,
///<summary>manual</summary>
Manual = 1,
///<summary>normal program</summary>
Normal = 2,
///<summary>aperture priority</summary>
Aperture = 3,
///<summary>shutter priority</summary>
Shutter = 4,
///<summary>creative program (biased toward depth of field)</summary>
Creative = 5,
///<summary>action program (biased toward fast shutter speed)</summary>
Action = 6,
///<summary>portrait mode (for close-up photos with the background out of focus)</summary>
Portrait = 7,
///<summary>landscape mode (for landscape photos with the background in focus)</summary>
Landscape = 8,
///<summary>9 to 255 - reserved</summary>
Reserved = 9
}
///<summary>
/// Metering mode
///</summary>
public enum MeteringMode: ushort
{
///<summary>Unknown</summary>
Unknown = 0,
///<summary>Average</summary>
Average = 1,
///<summary>Center weighted average</summary>
CenterWeightedAverage = 2,
///<summary>Spot</summary>
Spot = 3,
///<summary>Multi Spot</summary>
MultiSpot = 4,
///<summary>Pattern</summary>
Pattern = 5,
///<summary>Partial</summary>
Partial = 6,
///<summary>Other</summary>
Other = 255
}
///<summary>
/// Specifies the data type of the values stored in the value data member of that same PropertyItem object.
///</summary>
public enum PropertyTagType: short
{
///<summary>Specifies that the format is 4 bits per pixel, indexed.</summary>
PixelFormat4bppIndexed = 0,
///<summary>Specifies that the value data member is an array of bytes.</summary>
Byte = 1,
///<summary>Specifies that the value data member is a null-terminated ASCII string. If you set the type data member of a PropertyItem object to PropertyTagTypeASCII, you should set the length data member to the length of the string including the NULL terminator. For example, the string HELLO would have a length of 6.</summary>
ASCII = 2,
///<summary>Specifies that the value data member is an array of unsigned short (16-bit) integers.</summary>
Short = 3,
///<summary>Specifies that the value data member is an array of unsigned long (32-bit) integers.</summary>
Long = 4,
///<summary>Specifies that the value data member is an array of pairs of unsigned long integers. Each pair represents a fraction; the first integer is the numerator and the second integer is the denominator.</summary>
Rational = 5,
///<summary>Specifies that the value data member is an array of bytes that can hold values of any data type.</summary>
Undefined = 7,
///<summary>Specifies that the value data member is an array of signed long (32-bit) integers.</summary>
SLONG = 9,
///<summary>Specifies that the value data member is an array of pairs of signed long integers. Each pair represents a fraction; the first integer is the numerator and the second integer is the denominator.</summary>
SRational = 10
}
///<summary>
/// The following Enumeration gives list (and descriptions) of the property items supported in EXIF format.
///</summary>
public enum PropertyTagId: int
{
///<summary>Null-terminated character string that specifies the name of the person who created the image.</summary>
Artist = 0x013B ,
///<summary>Number of bits per color component. See also SamplesPerPixel.</summary>
BitsPerSample = 0x0102 ,
///<summary></summary>
CellHeight = 0x0109 ,
///<summary></summary>
CellWidth = 0x0108 ,
///<summary></summary>
ChrominanceTable = 0x5091 ,
///<summary></summary>
ColorMap = 0x0140 ,
///<summary></summary>
ColorTransferFunction = 0x501A ,
///<summary></summary>
Compression = 0x0103 ,
///<summary></summary>
Copyright = 0x8298 ,
///<summary></summary>
DateTime = 0x0132 ,
///<summary></summary>
DocumentName = 0x010D ,
///<summary></summary>
DotRange = 0x0150 ,
///<summary></summary>
EquipMake = 0x010F ,
///<summary></summary>
EquipModel = 0x0110 ,
///<summary></summary>
ExifAperture = 0x9202 ,
///<summary></summary>
ExifBrightness = 0x9203 ,
///<summary></summary>
ExifCfaPattern = 0xA302 ,
///<summary></summary>
ExifColorSpace = 0xA001 ,
///<summary></summary>
ExifCompBPP = 0x9102 ,
///<summary></summary>
ExifCompConfig = 0x9101 ,
///<summary></summary>
ExifDTDigitized = 0x9004 ,
///<summary></summary>
ExifDTDigSS = 0x9292 ,
///<summary></summary>
ExifDTOrig = 0x9003 ,
///<summary></summary>
ExifDTOrigSS = 0x9291 ,
///<summary></summary>
ExifDTSubsec = 0x9290 ,
///<summary></summary>
ExifExposureBias = 0x9204 ,
///<summary></summary>
ExifExposureIndex = 0xA215 ,
///<summary></summary>
ExifExposureProg = 0x8822 ,
///<summary></summary>
ExifExposureTime = 0x829A ,
///<summary></summary>
ExifFileSource = 0xA300 ,
///<summary></summary>
ExifFlash = 0x9209 ,
///<summary></summary>
ExifFlashEnergy = 0xA20B ,
///<summary></summary>
ExifFNumber = 0x829D ,
///<summary></summary>
ExifFocalLength = 0x920A ,
///<summary></summary>
ExifFocalResUnit = 0xA210 ,
///<summary></summary>
ExifFocalXRes = 0xA20E ,
///<summary></summary>
ExifFocalYRes = 0xA20F ,
///<summary></summary>
ExifFPXVer = 0xA000 ,
///<summary></summary>
ExifIFD = 0x8769 ,
///<summary></summary>
ExifInterop = 0xA005 ,
///<summary></summary>
ExifISOSpeed = 0x8827 ,
///<summary></summary>
ExifLightSource = 0x9208 ,
///<summary></summary>
ExifMakerNote = 0x927C ,
///<summary></summary>
ExifMaxAperture = 0x9205 ,
///<summary></summary>
ExifMeteringMode = 0x9207 ,
///<summary></summary>
ExifOECF = 0x8828 ,
///<summary></summary>
ExifPixXDim = 0xA002 ,
///<summary></summary>
ExifPixYDim = 0xA003 ,
///<summary></summary>
ExifRelatedWav = 0xA004 ,
///<summary></summary>
ExifSceneType = 0xA301 ,
///<summary></summary>
ExifSensingMethod = 0xA217 ,
///<summary></summary>
ExifShutterSpeed = 0x9201 ,
///<summary></summary>
ExifSpatialFR = 0xA20C ,
///<summary></summary>
ExifSpectralSense = 0x8824 ,
///<summary></summary>
ExifSubjectDist = 0x9206 ,
///<summary></summary>
ExifSubjectLoc = 0xA214 ,
///<summary></summary>
ExifUserComment = 0x9286 ,
///<summary></summary>
ExifVer = 0x9000 ,
///<summary></summary>
ExtraSamples = 0x0152 ,
///<summary></summary>
FillOrder = 0x010A ,
///<summary></summary>
FrameDelay = 0x5100 ,
///<summary></summary>
FreeByteCounts = 0x0121 ,
///<summary></summary>
FreeOffset = 0x0120 ,
///<summary></summary>
Gamma = 0x0301 ,
///<summary></summary>
GlobalPalette = 0x5102 ,
///<summary></summary>
GpsAltitude = 0x0006 ,
///<summary></summary>
GpsAltitudeRef = 0x0005 ,
///<summary></summary>
GpsDestBear = 0x0018 ,
///<summary></summary>
GpsDestBearRef = 0x0017 ,
///<summary></summary>
GpsDestDist = 0x001A ,
///<summary></summary>
GpsDestDistRef = 0x0019 ,
///<summary></summary>
GpsDestLat = 0x0014 ,
///<summary></summary>
GpsDestLatRef = 0x0013 ,
///<summary></summary>
GpsDestLong = 0x0016 ,
///<summary></summary>
GpsDestLongRef = 0x0015 ,
///<summary></summary>
GpsGpsDop = 0x000B ,
///<summary></summary>
GpsGpsMeasureMode = 0x000A ,
///<summary></summary>
GpsGpsSatellites = 0x0008 ,
///<summary></summary>
GpsGpsStatus = 0x0009 ,
///<summary></summary>
GpsGpsTime = 0x0007 ,
///<summary></summary>
GpsIFD = 0x8825 ,
///<summary></summary>
GpsImgDir = 0x0011 ,
///<summary></summary>
GpsImgDirRef = 0x0010 ,
///<summary></summary>
GpsLatitude = 0x0002 ,
///<summary></summary>
GpsLatitudeRef = 0x0001 ,
///<summary></summary>
GpsLongitude = 0x0004 ,
///<summary></summary>
GpsLongitudeRef = 0x0003 ,
///<summary></summary>
GpsMapDatum = 0x0012 ,
///<summary></summary>
GpsSpeed = 0x000D ,
///<summary></summary>
GpsSpeedRef = 0x000C ,
///<summary></summary>
GpsTrack = 0x000F ,
///<summary></summary>
GpsTrackRef = 0x000E ,
///<summary></summary>
GpsVer = 0x0000 ,
///<summary></summary>
GrayResponseCurve = 0x0123 ,
///<summary></summary>
GrayResponseUnit = 0x0122 ,
///<summary></summary>
GridSize = 0x5011 ,
///<summary></summary>
HalftoneDegree = 0x500C ,
///<summary></summary>
HalftoneHints = 0x0141 ,
///<summary></summary>
HalftoneLPI = 0x500A ,
///<summary></summary>
HalftoneLPIUnit = 0x500B ,
///<summary></summary>
HalftoneMisc = 0x500E ,
///<summary></summary>
HalftoneScreen = 0x500F ,
///<summary></summary>
HalftoneShape = 0x500D ,
///<summary></summary>
HostComputer = 0x013C ,
///<summary></summary>
ICCProfile = 0x8773 ,
///<summary></summary>
ICCProfileDescriptor = 0x0302 ,
///<summary></summary>
ImageDescription = 0x010E ,
///<summary></summary>
ImageHeight = 0x0101 ,
///<summary></summary>
ImageTitle = 0x0320 ,
///<summary></summary>
ImageWidth = 0x0100 ,
///<summary></summary>
IndexBackground = 0x5103 ,
///<summary></summary>
IndexTransparent = 0x5104 ,
///<summary></summary>
InkNames = 0x014D ,
///<summary></summary>
InkSet = 0x014C ,
///<summary></summary>
JPEGACTables = 0x0209 ,
///<summary></summary>
JPEGDCTables = 0x0208 ,
///<summary></summary>
JPEGInterFormat = 0x0201 ,
///<summary></summary>
JPEGInterLength = 0x0202 ,
///<summary></summary>
JPEGLosslessPredictors = 0x0205 ,
///<summary></summary>
JPEGPointTransforms = 0x0206 ,
///<summary></summary>
JPEGProc = 0x0200 ,
///<summary></summary>
JPEGQTables = 0x0207 ,
///<summary></summary>
JPEGQuality = 0x5010 ,
///<summary></summary>
JPEGRestartInterval = 0x0203 ,
///<summary></summary>
LoopCount = 0x5101 ,
///<summary></summary>
LuminanceTable = 0x5090 ,
///<summary></summary>
MaxSampleValue = 0x0119 ,
///<summary></summary>
MinSampleValue = 0x0118 ,
///<summary></summary>
NewSubfileType = 0x00FE ,
///<summary></summary>
NumberOfInks = 0x014E ,
///<summary></summary>
Orientation = 0x0112 ,
///<summary></summary>
PageName = 0x011D ,
///<summary></summary>
PageNumber = 0x0129 ,
///<summary></summary>
PaletteHistogram = 0x5113 ,
///<summary></summary>
PhotometricInterp = 0x0106 ,
///<summary></summary>
PixelPerUnitX = 0x5111 ,
///<summary></summary>
PixelPerUnitY = 0x5112 ,
///<summary></summary>
PixelUnit = 0x5110 ,
///<summary></summary>
PlanarConfig = 0x011C ,
///<summary></summary>
Predictor = 0x013D ,
///<summary></summary>
PrimaryChromaticities = 0x013F ,
///<summary></summary>
PrintFlags = 0x5005 ,
///<summary></summary>
PrintFlagsBleedWidth = 0x5008 ,
///<summary></summary>
PrintFlagsBleedWidthScale = 0x5009 ,
///<summary></summary>
PrintFlagsCrop = 0x5007 ,
///<summary></summary>
PrintFlagsVersion = 0x5006 ,
///<summary></summary>
REFBlackWhite = 0x0214 ,
///<summary></summary>
ResolutionUnit = 0x0128 ,
///<summary></summary>
ResolutionXLengthUnit = 0x5003 ,
///<summary></summary>
ResolutionXUnit = 0x5001 ,
///<summary></summary>
ResolutionYLengthUnit = 0x5004 ,
///<summary></summary>
ResolutionYUnit = 0x5002 ,
///<summary></summary>
RowsPerStrip = 0x0116 ,
///<summary></summary>
SampleFormat = 0x0153 ,
///<summary></summary>
SamplesPerPixel = 0x0115 ,
///<summary></summary>
SMaxSampleValue = 0x0155 ,
///<summary></summary>
SMinSampleValue = 0x0154 ,
///<summary></summary>
SoftwareUsed = 0x0131 ,
///<summary></summary>
SRGBRenderingIntent = 0x0303 ,
///<summary></summary>
StripBytesCount = 0x0117 ,
///<summary></summary>
StripOffsets = 0x0111 ,
///<summary></summary>
SubfileType = 0x00FF ,
///<summary></summary>
T4Option = 0x0124 ,
///<summary></summary>
T6Option = 0x0125 ,
///<summary></summary>
TargetPrinter = 0x0151 ,
///<summary></summary>
ThreshHolding = 0x0107 ,
///<summary></summary>
ThumbnailArtist = 0x5034 ,
///<summary></summary>
ThumbnailBitsPerSample = 0x5022 ,
///<summary></summary>
ThumbnailColorDepth = 0x5015 ,
///<summary></summary>
ThumbnailCompressedSize = 0x5019 ,
///<summary></summary>
ThumbnailCompression = 0x5023 ,
///<summary></summary>
ThumbnailCopyRight = 0x503B ,
///<summary></summary>
ThumbnailData = 0x501B ,
///<summary></summary>
ThumbnailDateTime = 0x5033 ,
///<summary></summary>
ThumbnailEquipMake = 0x5026 ,
///<summary></summary>
ThumbnailEquipModel = 0x5027 ,
///<summary></summary>
ThumbnailFormat = 0x5012 ,
///<summary></summary>
ThumbnailHeight = 0x5014 ,
///<summary></summary>
ThumbnailImageDescription= 0x5025 ,
///<summary></summary>
ThumbnailImageHeight = 0x5021 ,
///<summary></summary>
ThumbnailImageWidth = 0x5020 ,
///<summary></summary>
ThumbnailOrientation = 0x5029 ,
///<summary></summary>
ThumbnailPhotometricInterp= 0x5024 ,
///<summary></summary>
ThumbnailPlanarConfig = 0x502F ,
///<summary></summary>
ThumbnailPlanes = 0x5016 ,
///<summary></summary>
ThumbnailPrimaryChromaticities= 0x5036 ,
///<summary></summary>
ThumbnailRawBytes = 0x5017 ,
///<summary></summary>
ThumbnailRefBlackWhite = 0x503A ,
///<summary></summary>
ThumbnailResolutionUnit = 0x5030 ,
///<summary></summary>
ThumbnailResolutionX = 0x502D ,
///<summary></summary>
ThumbnailResolutionY = 0x502E ,
///<summary></summary>
ThumbnailRowsPerStrip = 0x502B ,
///<summary></summary>
ThumbnailSamplesPerPixel= 0x502A ,
///<summary></summary>
ThumbnailSize = 0x5018 ,
///<summary></summary>
ThumbnailSoftwareUsed = 0x5032 ,
///<summary></summary>
ThumbnailStripBytesCount= 0x502C ,
///<summary></summary>
ThumbnailStripOffsets = 0x5028 ,
///<summary></summary>
ThumbnailTransferFunction= 0x5031 ,
///<summary></summary>
ThumbnailWhitePoint = 0x5035 ,
///<summary></summary>
ThumbnailWidth = 0x5013 ,
///<summary></summary>
ThumbnailYCbCrCoefficients= 0x5037 ,
///<summary></summary>
ThumbnailYCbCrPositioning= 0x5039 ,
///<summary></summary>
ThumbnailYCbCrSubsampling= 0x5038 ,
///<summary></summary>
TileByteCounts = 0x0145 ,
///<summary></summary>
TileLength = 0x0143 ,
///<summary></summary>
TileOffset = 0x0144 ,
///<summary></summary>
TileWidth = 0x0142 ,
///<summary></summary>
TransferFunction = 0x012D ,
///<summary></summary>
TransferRange = 0x0156 ,
///<summary></summary>
WhitePoint = 0x013E ,
///<summary></summary>
XPosition = 0x011E ,
///<summary></summary>
XResolution = 0x011A ,
///<summary></summary>
YCbCrCoefficients = 0x0211 ,
///<summary></summary>
YCbCrPositioning = 0x0213 ,
///<summary></summary>
YCbCrSubsampling = 0x0212 ,
///<summary></summary>
YPosition = 0x011F ,
///<summary></summary>
YResolution = 0x011B
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Collections.ObjectModel
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
[Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class Collection<T>: IList<T>, IList, IReadOnlyList<T>
{
IList<T> items;
[NonSerialized]
private Object _syncRoot;
public Collection() {
items = new List<T>();
}
public Collection(IList<T> list) {
if (list == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
items = list;
}
public int Count {
get { return items.Count; }
}
protected IList<T> Items {
get { return items; }
}
public T this[int index] {
get { return items[index]; }
set {
if( items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
if (index < 0 || index >= items.Count) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
SetItem(index, value);
}
}
public void Add(T item) {
if( items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
int index = items.Count;
InsertItem(index, item);
}
public void Clear() {
if( items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ClearItems();
}
public void CopyTo(T[] array, int index) {
items.CopyTo(array, index);
}
public bool Contains(T item) {
return items.Contains(item);
}
public IEnumerator<T> GetEnumerator() {
return items.GetEnumerator();
}
public int IndexOf(T item) {
return items.IndexOf(item);
}
public void Insert(int index, T item) {
if (items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
if (index < 0 || index > items.Count) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
InsertItem(index, item);
}
public bool Remove(T item) {
if( items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
int index = items.IndexOf(item);
if (index < 0) return false;
RemoveItem(index);
return true;
}
public void RemoveAt(int index) {
if( items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
if (index < 0 || index >= items.Count) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
RemoveItem(index);
}
protected virtual void ClearItems() {
items.Clear();
}
protected virtual void InsertItem(int index, T item) {
items.Insert(index, item);
}
protected virtual void RemoveItem(int index) {
items.RemoveAt(index);
}
protected virtual void SetItem(int index, T item) {
items[index] = item;
}
bool ICollection<T>.IsReadOnly {
get {
return items.IsReadOnly;
}
}
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable)items).GetEnumerator();
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get {
if( _syncRoot == null) {
ICollection c = items as ICollection;
if( c != null) {
_syncRoot = c.SyncRoot;
}
else {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if( array.GetLowerBound(0) != 0 ) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 ) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
T[] tArray = array as T[];
if (tArray != null) {
items.CopyTo(tArray , index);
}
else {
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if( objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
int count = items.Count;
try {
for (int i = 0; i < count; i++) {
objects[index++] = items[i];
}
}
catch(ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
object IList.this[int index] {
get { return items[index]; }
set {
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try {
this[index] = (T)value;
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
}
bool IList.IsReadOnly {
get {
return items.IsReadOnly;
}
}
bool IList.IsFixedSize {
get {
// There is no IList<T>.IsFixedSize, so we must assume that only
// readonly collections are fixed size, if our internal item
// collection does not implement IList. Note that Array implements
// IList, and therefore T[] and U[] will be fixed-size.
IList list = items as IList;
if(list != null)
{
return list.IsFixedSize;
}
return items.IsReadOnly;
}
}
int IList.Add(object value) {
if( items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try {
Add((T)value);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
return this.Count - 1;
}
bool IList.Contains(object value) {
if(IsCompatibleObject(value)) {
return Contains((T) value);
}
return false;
}
int IList.IndexOf(object value) {
if(IsCompatibleObject(value)) {
return IndexOf((T)value);
}
return -1;
}
void IList.Insert(int index, object value) {
if( items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try {
Insert(index, (T)value);
}
catch (InvalidCastException) {
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
void IList.Remove(object value) {
if( items.IsReadOnly) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
if(IsCompatibleObject(value)) {
Remove((T) value);
}
}
private static bool IsCompatibleObject(object value) {
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
}
}
| |
namespace KingSurvival.Web.Areas.HelpPage
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator simpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return this.GenerateObject(type, new Dictionary<Type, object>());
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return this.simpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private class SimpleTypeObjectGenerator
{
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
private long index = 0;
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++this.index);
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(bool), index => true },
{ typeof(byte), index => (byte)64 },
{ typeof(char), index => (char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(decimal), index => (decimal)index },
{ typeof(double), index => (double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(short), index => (short)(index % short.MaxValue) },
{ typeof(int), index => (int)(index % int.MaxValue) },
{ typeof(long), index => (long)index },
{ typeof(object), index => new object() },
{ typeof(sbyte), index => (sbyte)64 },
{ typeof(float), index => (float)(index + 0.1) },
{
typeof(string), index =>
{
return string.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(ushort), index => (ushort)(index % ushort.MaxValue) },
{ typeof(uint), index => (uint)(index % uint.MaxValue) },
{ typeof(ulong), index => (ulong)index },
{
typeof(Uri), index =>
{
return new Uri(string.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyFile
{
using Microsoft.Rest;
using Models;
/// <summary>
/// Files operations.
/// </summary>
public partial class Files : Microsoft.Rest.IServiceOperations<AutoRestSwaggerBATFileService>, IFiles
{
/// <summary>
/// Initializes a new instance of the Files class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Files(AutoRestSwaggerBATFileService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATFileService
/// </summary>
public AutoRestSwaggerBATFileService Client { get; private set; }
/// <summary>
/// Get file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.IO.Stream>> GetFileWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetFile", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/nonempty").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a large file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.IO.Stream>> GetFileLargeWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetFileLarge", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/verylarge").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get empty file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.IO.Stream>> GetEmptyFileWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetEmptyFile", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/empty").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright 2013-2015 Serilog Contributors
//
// 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.ComponentModel;
using Serilog.Core;
using Serilog.Core.Enrichers;
using Serilog.Events;
#if ASYNCLOCAL
using System.Threading;
#elif REMOTING
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting.Messaging;
#endif
namespace Serilog.Context
{
/// <summary>
/// Holds ambient properties that can be attached to log events. To
/// configure, use the <see cref="Serilog.Configuration.LoggerEnrichmentConfiguration.FromLogContext"/> method.
/// </summary>
/// <example>
/// Configuration:
/// <code lang="C#">
/// var log = new LoggerConfiguration()
/// .Enrich.FromLogContext()
/// ...
/// </code>
/// Usage:
/// <code lang="C#">
/// using (LogContext.PushProperty("MessageId", message.Id))
/// {
/// Log.Information("The MessageId property will be attached to this event");
/// }
/// </code>
/// </example>
/// <remarks>The scope of the context is the current logical thread, using AsyncLocal
/// (and so is preserved across async/await calls).</remarks>
public static class LogContext
{
#if ASYNCLOCAL
static readonly AsyncLocal<ImmutableStack<ILogEventEnricher>> Data = new AsyncLocal<ImmutableStack<ILogEventEnricher>>();
#elif REMOTING
static readonly string DataSlotName = typeof(LogContext).FullName + "@" + Guid.NewGuid();
#else // DOTNET_51
[ThreadStatic]
static ImmutableStack<ILogEventEnricher> Data;
#endif
/// <summary>
/// Push a property onto the context, returning an <see cref="IDisposable"/>
/// that must later be used to remove the property, along with any others that
/// may have been pushed on top of it and not yet popped. The property must
/// be popped from the same thread/logical call context.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="value">The value of the property.</param>
/// <returns>A handle to later remove the property from the context.</returns>
/// <param name="destructureObjects">If true, and the value is a non-primitive, non-array type,
/// then the value will be converted to a structure; otherwise, unknown types will
/// be converted to scalars, which are generally stored as strings.</param>
/// <returns>A token that must be disposed, in order, to pop properties back off the stack.</returns>
public static IDisposable PushProperty(string name, object value, bool destructureObjects = false)
{
return Push(new PropertyEnricher(name, value, destructureObjects));
}
/// <summary>
/// Push an enricher onto the context, returning an <see cref="IDisposable"/>
/// that must later be used to remove the property, along with any others that
/// may have been pushed on top of it and not yet popped. The property must
/// be popped from the same thread/logical call context.
/// </summary>
/// <param name="enricher">An enricher to push onto the log context</param>
/// <returns>A token that must be disposed, in order, to pop properties back off the stack.</returns>
/// <exception cref="ArgumentNullException"></exception>
public static IDisposable Push(ILogEventEnricher enricher)
{
if (enricher == null) throw new ArgumentNullException(nameof(enricher));
var stack = GetOrCreateEnricherStack();
var bookmark = new ContextStackBookmark(stack);
Enrichers = stack.Push(enricher);
return bookmark;
}
/// <summary>
/// Push multiple enrichers onto the context, returning an <see cref="IDisposable"/>
/// that must later be used to remove the property, along with any others that
/// may have been pushed on top of it and not yet popped. The property must
/// be popped from the same thread/logical call context.
/// </summary>
/// <seealso cref="PropertyEnricher"/>.
/// <param name="enrichers">Enrichers to push onto the log context</param>
/// <returns>A token that must be disposed, in order, to pop properties back off the stack.</returns>
/// <exception cref="ArgumentNullException"></exception>
public static IDisposable Push(params ILogEventEnricher[] enrichers)
{
if (enrichers == null) throw new ArgumentNullException(nameof(enrichers));
var stack = GetOrCreateEnricherStack();
var bookmark = new ContextStackBookmark(stack);
for (var i = 0; i < enrichers.Length; ++i)
stack = stack.Push(enrichers[i]);
Enrichers = stack;
return bookmark;
}
/// <summary>
/// Push enrichers onto the log context. This method is obsolete, please
/// use <see cref="Push(Serilog.Core.ILogEventEnricher[])"/> instead.
/// </summary>
/// <param name="properties">Enrichers to push onto the log context</param>
/// <returns>A token that must be disposed, in order, to pop properties back off the stack.</returns>
/// <exception cref="ArgumentNullException"></exception>
[Obsolete("Please use `LogContext.Push(properties)` instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static IDisposable PushProperties(params ILogEventEnricher[] properties)
{
return Push(properties);
}
/// <summary>
/// Obtain an enricher that represents the current contents of the <see cref="LogContext"/>. This
/// can be pushed back onto the context in a different location/thread when required.
/// </summary>
/// <returns>An enricher that represents the current contents of the <see cref="LogContext"/>.</returns>
public static ILogEventEnricher Clone()
{
var stack = GetOrCreateEnricherStack();
return new SafeAggregateEnricher(stack);
}
/// <summary>
/// Remove all enrichers from the <see cref="LogContext"/>, returning an <see cref="IDisposable"/>
/// that must later be used to restore enrichers that were on the stack before <see cref="Suspend"/> was called.
/// </summary>
/// <returns>A token that must be disposed, in order, to restore properties back to the stack.</returns>
public static IDisposable Suspend()
{
var stack = GetOrCreateEnricherStack();
var bookmark = new ContextStackBookmark(stack);
Enrichers = ImmutableStack<ILogEventEnricher>.Empty;
return bookmark;
}
/// <summary>
/// Remove all enrichers from <see cref="LogContext"/> for the current async scope.
/// </summary>
public static void Reset()
{
if (Enrichers != null && Enrichers != ImmutableStack<ILogEventEnricher>.Empty)
{
Enrichers = ImmutableStack<ILogEventEnricher>.Empty;
}
}
static ImmutableStack<ILogEventEnricher> GetOrCreateEnricherStack()
{
var enrichers = Enrichers;
if (enrichers == null)
{
enrichers = ImmutableStack<ILogEventEnricher>.Empty;
Enrichers = enrichers;
}
return enrichers;
}
internal static void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var enrichers = Enrichers;
if (enrichers == null || enrichers == ImmutableStack<ILogEventEnricher>.Empty)
return;
foreach (var enricher in enrichers)
{
enricher.Enrich(logEvent, propertyFactory);
}
}
sealed class ContextStackBookmark : IDisposable
{
readonly ImmutableStack<ILogEventEnricher> _bookmark;
public ContextStackBookmark(ImmutableStack<ILogEventEnricher> bookmark)
{
_bookmark = bookmark;
}
public void Dispose()
{
Enrichers = _bookmark;
}
}
#if ASYNCLOCAL
static ImmutableStack<ILogEventEnricher> Enrichers
{
get => Data.Value;
set => Data.Value = value;
}
#elif REMOTING
static ImmutableStack<ILogEventEnricher> Enrichers
{
get
{
var objectHandle = CallContext.LogicalGetData(DataSlotName) as ObjectHandle;
return objectHandle?.Unwrap() as ImmutableStack<ILogEventEnricher>;
}
set
{
if (CallContext.LogicalGetData(DataSlotName) is IDisposable oldHandle)
{
oldHandle.Dispose();
}
CallContext.LogicalSetData(DataSlotName, new DisposableObjectHandle(value));
}
}
sealed class DisposableObjectHandle : ObjectHandle, IDisposable
{
static readonly ISponsor LifeTimeSponsor = new ClientSponsor();
public DisposableObjectHandle(object o) : base(o)
{
}
public override object InitializeLifetimeService()
{
var lease = (ILease)base.InitializeLifetimeService();
lease.Register(LifeTimeSponsor);
return lease;
}
public void Dispose()
{
if (GetLifetimeService() is ILease lease)
{
lease.Unregister(LifeTimeSponsor);
}
}
}
#else // DOTNET_51
static ImmutableStack<ILogEventEnricher> Enrichers
{
get => Data;
set => Data = value;
}
#endif
}
}
| |
//
// 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.Collections;
using System.Drawing;
using System.Runtime.CompilerServices;
namespace Encog.App.Quant.Loader.OpenQuant.Data
{
/// <summary>
/// This holds the various data used by Openquant
/// Bars, and various custom series.
/// </summary>
public class Data
{
/// <summary>
/// Different data , a bar holds
/// </summary>
public enum BarData
{
Close,
Open,
High,
Low,
Median,
Typical,
Weighted,
Volume,
OpenInt
}
/// <summary>
/// Different possible prices on a bar.
/// </summary>
public enum BarPrice
{
High,
Low,
Open,
Close,
Median,
Typical,
Weighted
}
public enum BarSlycing
{
Normal,
Equally
}
/// <summary>
/// The different bar types
/// </summary>
public enum BarType : byte
{
/// <summary>
/// Dynamic types.
/// </summary>
Dynamic = 5,
/// <summary>
/// Range bars
/// </summary>
Range = 4,
/// <summary>
/// Tick bars
/// </summary>
Tick = 2,
/// <summary>
/// Time bars (open, high, low, close)
/// </summary>
Time = 1,
Volume = 3
}
/// <summary>
/// Adds two numbers.
/// </summary>
private Func<int, int, int> Add = (x, y) => x + y;
[Serializable]
public class Bar : ICloneable
{
/// <summary>
/// Initializes a new instance of the <see cref="Bar" /> class.
/// </summary>
/// <param name="barType">Type of the bar.</param>
/// <param name="size">The size.</param>
/// <param name="beginTime">The begin time.</param>
/// <param name="endTime">The end time.</param>
/// <param name="open">The open.</param>
/// <param name="high">The high.</param>
/// <param name="low">The low.</param>
/// <param name="close">The close.</param>
/// <param name="volume">The volume.</param>
/// <param name="openInt">The open int.</param>
public Bar(BarType barType, long size, DateTime beginTime, DateTime endTime, double open, double high,
double low, double close, long volume, long openInt)
{
this.barType = barType;
Size = size;
BeginTime = beginTime;
EndTime = endTime;
Open = open;
High = high;
Low = low;
Close = close;
Volume = volume;
OpenInt = openInt;
ProviderId = 0;
color = Color.Empty;
IsComplete = false;
DateKind = beginTime.Kind;
DateTimeKind kind = beginTime.Kind;
DateTimeKind kind2 = endTime.Kind;
}
/// <summary>
/// Initializes a new instance of the <see cref="Bar" /> class.
/// </summary>
/// <param name="size">The size.</param>
/// <param name="open">The open.</param>
/// <param name="high">The high.</param>
/// <param name="low">The low.</param>
/// <param name="close">The close.</param>
public Bar(long size, double open, double high, double low, double close)
{
barType = barType;
Size = size;
BeginTime = beginTime;
Open = open;
High = high;
Low = low;
Close = close;
ProviderId = 0;
color = Color.Empty;
IsComplete = false;
}
#region ICloneable Members
public object Clone()
{
return MemberwiseClone();
}
#endregion
public DateTime DateTime { get; set; }
public double Close { get; set; }
public double Open { get; set; }
public double High { get; set; }
public double Low { get; set; }
public DateTime BeginTime { get; set; }
protected DateTime EndTime { get; set; } //end time for this bar.
public TimeSpan Duration { get; set; }
// Fields
protected BarType barType { get; set; }
protected DateTime beginTime { get; set; } //Begin time for this bar
protected Color color { get; set; } //Color the bar should be drawed
protected bool IsComplete { get; set; } // is the bar complete.
protected long OpenInt { get; set; } // open interests on othis bar.
protected byte ProviderId { get; set; } // provider for this bar (a byte , e.g Simulated executions 1.
protected long Size { get; set; } // the size : Lenght in seconds of this bar.
protected long Volume { get; set; } // the volume of this bar.
protected DateTimeKind DateKind { get; set; } //Bar kind.
protected double Weighted { get; set; }
protected double Median { get; set; }
protected double Typical { get; set; }
/// <summary>
/// Gets the last price for a bar price option
/// </summary>
/// <param name="option">The option.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public double GetPrice(BarPrice option)
{
switch (option)
{
case BarPrice.High:
return High;
case BarPrice.Low:
return Low;
case BarPrice.Open:
return Open;
case BarPrice.Close:
return Close;
case BarPrice.Median:
return Median;
case BarPrice.Typical:
return Typical;
case BarPrice.Weighted:
return Weighted;
}
return 0.0;
}
}
/// <summary>
/// holds arrays of bars
/// </summary>
public class BarArray : IEnumerable
{
// Methods
public DataArray BarSeries;
[MethodImpl(MethodImplOptions.NoInlining)]
public BarArray()
{
BarSeries = new DataArray();
}
// Properties
/// <summary>
/// Gets the <see cref="Bar" /> at the specified index.
/// </summary>
public Bar this[int index]
{
[MethodImpl(MethodImplOptions.NoInlining)] get { return this[index]; }
}
public IEnumerator GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Adds the specified bar.
/// </summary>
/// <param name="bar">The bar.</param>
public void Add(Bar bar)
{
BarSeries.Add(bar);
}
}
public interface IDataObject
{
// Properties
DateTime DateTime { get; set; }
byte ProviderId { get; set; }
}
}
}
| |
// This file is part of the OWASP O2 Platform (http://www.owasp.org/index.php/OWASP_O2_Platform) and is released under the Apache 2.0 License (http://www.apache.org/licenses/LICENSE-2.0)
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace FluentSharp.CoreLib.API
{
public class O2Proxy : MarshalByRefObject
{
public bool InvokeInStaThread { get; set; }
public bool InvokeInMtaThread { get; set; }
public override string ToString()
{
var currentDomain = nameOfCurrentDomain();
return currentDomain ?? ""; // to deal with '...Attempted to read or write protected memory..' issue
}
// reflection helpers
public List<String> getAssemblies()
{
return getAssemblies(false);
}
public List<String> getAssemblies(bool showFulName)
{
var assemblies = new List<String>();
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
if (showFulName)
assemblies.Add(assembly.FullName);
else
assemblies.Add(assembly.GetName().Name);
return assemblies;
}
public List<String> getTypes(string assemblyName)
{
var types = new List<String>();
try
{
Assembly assembly = AppDomain.CurrentDomain.Load(assemblyName);
foreach (Type type in PublicDI.reflection.getTypes(assembly))
types.Add(type.Name);
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in getTypes");
}
return types;
}
public List<String> getMethods(string assemblyName, string typeName)
{
return getMethods(assemblyName, typeName, false, false);
}
public List<String> getMethods(string assemblyName, string typeName, bool onlyReturnStaticMethods,
bool onlyReturnMethodsWithNoParameters)
{
var methods = new List<String>();
try
{
Assembly assembly = AppDomain.CurrentDomain.Load(assemblyName);
Type type = PublicDI.reflection.getType(assembly, typeName);
foreach (MethodInfo method in PublicDI.reflection.getMethods(type))
if ((false == onlyReturnStaticMethods || method.IsStatic) &&
(false == onlyReturnMethodsWithNoParameters || method.GetParameters().Length == 0))
methods.Add(method.Name);
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in getTypes");
}
return methods;
}
// Methods to help basic testing
public string Property { get; set; }
public string returnConcatParamData(string paramDataString, int paramDataInt)
{
return paramDataString + paramDataInt;
}
public string nameOfCurrentDomain()
{
return AppDomain.CurrentDomain.FriendlyName;
}
public static string nameOfCurrentDomainStatic()
{
return AppDomain.CurrentDomain.FriendlyName;
}
public static void logInfo(string infoMessageToLog)
{
PublicDI.log.info(infoMessageToLog);
}
public static void logDebug(string debugMessageToLog)
{
PublicDI.log.debug(debugMessageToLog);
}
public static void logError(string errorMessageToLog)
{
PublicDI.log.error(errorMessageToLog);
}
/*public static void showMessageBox(string messageBoxText)
{
PublicDI.log.showMessageBox(messageBoxText);
}
public static DialogResult showMessageBox(string message, string messageBoxTitle,
MessageBoxButtons messageBoxButtons)
{
return PublicDI.log.showMessageBox(message, messageBoxTitle, messageBoxButtons);
}*/
// InstanceInvocation
public object instanceInvocation(string typeToLoad, string methodToExecute, object[] methodParams)
{
string assembly = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
return instanceInvocation(assembly, typeToLoad, methodToExecute, methodParams);
}
public object instanceInvocation(string assemblyToUse, string typeToLoad, string methodToExecute,
object[] methodParams)
{
try
{
Assembly assembly = AppDomain.CurrentDomain.Load(assemblyToUse);
if (assembly.isNull())
PublicDI.log.error("in instanceInvocation assembly was null : {0} {1}", assemblyToUse);
else
{
Type type = PublicDI.reflection.getType(assembly, typeToLoad);
if (type == null)
PublicDI.log.error("in instanceInvocation type was null : {0} {1}", assembly, typeToLoad);
else
{
object typeObject = PublicDI.reflection.createObject(assembly, type, methodParams);
if (typeObject == null)
PublicDI.log.error("in dynamicInvocation typeObject was null : {0} {1}", assembly, type);
else
{
if (methodToExecute == "")
// means we don't want to execute a method (i.e we called the constructore) so just want the current proxy
return typeObject;
MethodInfo method = PublicDI.reflection.getMethod(type, methodToExecute, methodParams);
if (method == null)
PublicDI.log.error("in instanceInvocation method was null : {0} {1}", type, methodToExecute);
else
{
object returnValue = null;
if (InvokeInStaThread)
{
O2Thread.staThread(() =>
{
returnValue = PublicDI.reflection.invoke(typeObject, method, methodParams);
}).Join();
return returnValue;
}
if (InvokeInMtaThread)
{
O2Thread.mtaThread(() =>
{
returnValue = PublicDI.reflection.invoke(typeObject, method, methodParams);
}).Join();
return returnValue;
}
return PublicDI.reflection.invoke(typeObject, method, methodParams);
}
}
}
}
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in instanceInvocation");
}
return null;
}
// staticInvocation
public object staticInvocation(string typeToLoad, string methodToExecute, object[] methodParams)
{
string assembly = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
return staticInvocation(assembly, typeToLoad, methodToExecute, methodParams);
}
public object staticInvocation(string assemblyToUse, string typeToLoad, string methodToExecute,
object[] methodParams)
{
try
{
//Assembly assembly = AppDomain.CurrentDomain.Load(assemblyToUse);
var assembly = assemblyToUse.assembly();
if (assembly == null)
PublicDI.log.error("in staticInvocation assembly was null : {0} {1}", assemblyToUse);
else
{
Type type = PublicDI.reflection.getType(assembly, typeToLoad);
if (type == null)
PublicDI.log.error("in staticInvocation type was null : {0} {1}", assembly, typeToLoad);
else
{
MethodInfo method = PublicDI.reflection.getMethod(type, methodToExecute, methodParams);
if (method == null)
PublicDI.log.error("in staticInvocation method was null : {0} {1}", type, methodToExecute);
else
{
object returnValue = null;
if (InvokeInStaThread)
{
O2Thread.staThread(() =>
{
returnValue = PublicDI.reflection.invoke(null, method, methodParams);
}).Join();
return returnValue;
}
if (InvokeInMtaThread)
{
O2Thread.mtaThread(() =>
{
returnValue = PublicDI.reflection.invoke(null, method, methodParams);
}).Join();
return returnValue;
}
returnValue = PublicDI.reflection.invoke(null, method, methodParams);
return returnValue;
}
}
}
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in instanceInvocation");
}
return null;
}
public bool staThread()
{
return InvokeInStaThread;
}
public void staThread(bool value)
{
InvokeInStaThread = value;
}
}
}
| |
/*
//
// INTEL CORPORATION PROPRIETARY INFORMATION
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Intel Corporation and may not be copied
// or disclosed except in accordance with the terms of that agreement.
// Copyright(c) 2003-2012 Intel Corporation. All Rights Reserved.
//
// Intel(R) Integrated Performance Primitives Using Intel(R) IPP
// in Microsoft* C# .NET for Windows* Sample
//
// By downloading and installing this sample, you hereby agree that the
// accompanying Materials are being provided to you under the terms and
// conditions of the End User License Agreement for the Intel(R) Integrated
// Performance Primitives product previously accepted by you. Please refer
// to the file ippEULA.rtf located in the root directory of your Intel(R) IPP
// product installation for more information.
//
*/
// generated automatically on Wed Feb 3 17:09:12 2010
using System;
using System.Security;
using System.Runtime.InteropServices;
namespace ipp {
//
// enums
//
public enum IpprIndexType {
ippNormInd = 3,
ippTriInd = 4,
};
public enum IpprSHType {
ipprSHNormDirect = 0,
ipprSHNormRecurr = 1,
};
public enum IpprKDTreeBuildAlg {
ippKDTBuildSimple = 0x499d3dc2,
ippKDTBuildPureSAH = 0x2d07705b,
};
//
// hidden or own structures
//
[StructLayout(LayoutKind.Sequential)] public struct IpprSHState {};
[StructLayout(LayoutKind.Sequential)] public struct IpprTriangleAccel {};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
unsafe public struct IpprPSAHBldContext {
public IpprKDTreeBuildAlg Alg;
public int MaxDepth;
public float QoS;
public int AvailMemory;
public float* Bounds;
};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)] public struct IpprSmplBldContext {
public IpprKDTreeBuildAlg Alg;
public int MaxDepth;
};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
unsafe public struct IpprIntersectContext {
public float* pBound;
public IpprTriangleAccel* pAccel;
public IpprKDTreeNode* pRootNode;
};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
public struct IpprKDTreeNode {
public int flag_k_ofs;
[StructLayout(LayoutKind.Explicit,CharSet=CharSet.Ansi)]
public struct tree_data {
[FieldOffset(0)] public float split;
[FieldOffset(0)] public int items;
}
};
unsafe public class rr {
internal const string libname = "ippr.dll";
//typedef float IppPoint3D_32f[3]
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprAddMulMul_32f_AC1P3IM ( float *point, float *pSrc0, float **pSrc1, int *pMask, float **pSrcDst, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprCastEye_32f ( float *imPlaneOrg, float *dW, float *dH, int wB, int hB, IppiSize cBlock, float **pDirection, IppiSize blockSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprCastReflectionRay_32f ( float **pInc, int *pMask, float **pSurfNorm, float **pReflect, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprCastShadowSO_32f ( float *pOrigin, float *pSurfDotIn, float **pSurfNorm, float **pSurfHit, int *pMask, float *pDotRay, float **pDirection, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprDistAttenuationSO_32f_M ( float *point, float **pSurfHit, int *pMask, float *pDist, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprDiv_32f_C1IM ( float *pSrc, int *pMask, float *pSrcDst, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprDotChangeNorm_32f_IM ( float **pSrc, int *pMask, float **pSrcDst, float *pDot, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprDot_32f_P3C1M ( float **pSrc0, float **pSrc1, int *pMask, float *pDot, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprFilterGetBufSize ( IpprVolume dstVolume, IpprVolume kernelVolume, int nChannel, int *pSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprFilter_16s_C1PV ( short **pSrc, int srcStep, short **pDst, int dstStep, IpprVolume dstVolume, int *pKernel, IpprVolume kernelVolume, IpprPoint anchor, int divisor, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname,EntryPoint="ipprGetLibVersion")] public static extern
int* xipprGetLibVersion ( );
public static IppLibraryVersion ipprGetLibVersion() {
return new IppLibraryVersion( xipprGetLibVersion() );
}
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprGetResizeCuboid ( IpprCuboid srcVOI, IpprCuboid *pDstCuboid, double xFactor, double yFactor, double zFactor, double xShift, double yShift, double zShift, int interpolation );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprHitPoint3DEpsM0_32f_M ( float **pOrigin, float **pDirection, float *pDist, int *pMask, float **pSurfHit, int len, float eps );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprHitPoint3DEpsS0_32f_M ( float *originEye, float **pDirection, float *pDist, int *pMask, float **pSurfHit, int len, float eps );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprIntersectAnySO_32f ( float *originEye, float **pDirection, int *pOccluder, int *pMask, IppiSize blockSize, IpprIntersectContext *pContext );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprIntersectEyeSO_32f ( float *originEye, float **pDirection, float *pDist, float **pHit, int *pTrngl, IpprIntersectContext *pContext, IppiSize blockSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprIntersectMO_32f ( float **pOrigin, float **pDirection, float *pDist, float **pHit, int *pTrngl, IpprIntersectContext *pContext, IppiSize blockSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprIntersectMultipleSO_32f ( float *originEye, float **pDirection, float *pDistance, float **pHit, int *pTrngl, IpprVolume blockVolume, IpprIntersectContext *pContext );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprKDTreeBuildAlloc ( IpprKDTreeNode **pDstKDTree, float *pSrcVert, int *pSrcTriInx, int SrcVertSize, int SrcTriSize, int *pDstKDTreeSize, char *pBldContext );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
void ipprKDTreeFree ( IpprKDTreeNode *pSrcKDTree );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprMul_32f_C1IM ( float *pSrc, int *pMask, float *pSrcDst, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprMul_32f_C1P3IM ( float *pSrc, int *pMask, float **pSrcDst, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprRemap_16u_C1PV ( ushort **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, float **pxMap, float **pyMap, float **pzMap, int mapStep, ushort **pDst, int dstStep, IpprVolume dstVolume, int interpolation );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprRemap_32f_C1PV ( float **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, float **pxMap, float **pyMap, float **pzMap, int mapStep, float **pDst, int dstStep, IpprVolume dstVolume, int interpolation );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprRemap_8u_C1PV ( byte **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, float **pxMap, float **pyMap, float **pzMap, int mapStep, byte **pDst, int dstStep, IpprVolume dstVolume, int interpolation );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprResizeGetBufSize ( IpprCuboid srcVOI, IpprCuboid dstVOI, int nChannel, int interpolation, int *pSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprResize_16u_C1PV ( ushort **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, ushort **pDst, int dstStep, IpprCuboid dstVOI, double xFactor, double yFactor, double zFactor, double xShift, double yShift, double zShift, int interpolation, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprResize_16u_C1V ( ushort *pSrc, IpprVolume srcVolume, int srcStep, int srcPlaneStep, IpprCuboid srcVOI, ushort *pDst, int dstStep, int dstPlaneStep, IpprCuboid dstVOI, double xFactor, double yFactor, double zFactor, double xShift, double yShift, double zShift, int interpolation, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprResize_32f_C1PV ( float **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, float **pDst, int dstStep, IpprCuboid dstVOI, double xFactor, double yFactor, double zFactor, double xShift, double yShift, double zShift, int interpolation, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprResize_32f_C1V ( float *pSrc, IpprVolume srcVolume, int srcStep, int srcPlaneStep, IpprCuboid srcVOI, float *pDst, int dstStep, int dstPlaneStep, IpprCuboid dstVOI, double xFactor, double yFactor, double zFactor, double xShift, double yShift, double zShift, int interpolation, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprResize_8u_C1PV ( byte **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, byte **pDst, int dstStep, IpprCuboid dstVOI, double xFactor, double yFactor, double zFactor, double xShift, double yShift, double zShift, int interpolation, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprResize_8u_C1V ( byte *pSrc, IpprVolume srcVolume, int srcStep, int srcPlaneStep, IpprCuboid srcVOI, byte *pDst, int dstStep, int dstPlaneStep, IpprCuboid dstVOI, double xFactor, double yFactor, double zFactor, double xShift, double yShift, double zShift, int interpolation, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHBand_32f ( float *pX, float *pY, float *pZ, uint N, float *pDstBandYlm, uint L );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHGetSize_32f ( uint maxL, IpprSHType shType, uint *pSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHInit_32f ( IpprSHState *pSHState, uint maxL, IpprSHType shType );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHTFwd_32f_C1I ( float *pX, float *pY, float *pZ, float *pSrc, uint N, float *pSrcDstClm, uint L, IpprSHState *pSHState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHTFwd_32f_C3P3I ( float *pX, float *pY, float *pZ, float *pSrc, uint N, float **pSrcDstClm, uint L, IpprSHState *pSHState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHTFwd_32f_P3I ( float *pX, float *pY, float *pZ, float **pSrc, uint N, float **pSrcDstClm, uint L, IpprSHState *pSHState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHTInv_32f_C1 ( float *pSrcClm, uint L, float *pX, float *pY, float *pZ, float *pDst, uint N, IpprSHState *pSHState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHTInv_32f_P3 ( float **pSrcClm, uint L, float *pX, float *pY, float *pZ, float **pDst, uint N, IpprSHState *pSHState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSHTInv_32f_P3C3 ( float **pSrcClm, uint L, float *pX, float *pY, float *pZ, float *pDst, uint N, IpprSHState *pSHState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSH_32f ( float *pX, float *pY, float *pZ, uint N, float *pDstYlm, uint L, IpprSHState *pSHState );
//typedef IppPoint3D_32f IppBox3D_32f[2]
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSetBoundBox_32f ( float *pVertCoor, int lenTri, float *pBound );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSurfFlatNormal_32f ( float *pTrnglNorm, int *pTrngl, float **pSurfNorm, int len );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprSurfSmoothNormal_32f ( float *pVertNorm, int *pIndexNorm, int *pTrngl, float **pHit, float **pSurfNorm, int len, IpprIndexType ippInd );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprTriangleAccelGetSize ( int *pTrnglAccelSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprTriangleAccelInit ( IpprTriangleAccel *pTrnglAccel, float *pVertexCoord, int *pTrnglIndex, int cntTrngl );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprTriangleNormal_32f ( float *pTrnglCoor, int *pTrnglIndex, float *pTrnglNorm, int lenTrngl );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprWarpAffineGetBufSize ( IpprCuboid srcVOI, IpprCuboid dstVOI, int nChannel, int interpolation, int *pSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprWarpAffine_16u_C1PV ( ushort **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, ushort **pDst, int dstStep, IpprCuboid dstVOI, double *coeffs, int interpolation, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprWarpAffine_32f_C1PV ( float **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, float **pDst, int dstStep, IpprCuboid dstVOI, double *coeffs, int interpolation, byte *pBuffer );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.rr.libname)] public static extern
IppStatus ipprWarpAffine_8u_C1PV ( byte **pSrc, IpprVolume srcVolume, int srcStep, IpprCuboid srcVOI, byte **pDst, int dstStep, IpprCuboid dstVOI, double *coeffs, int interpolation, byte *pBuffer );
};
};
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace Newtonsoft.Json
{
public static class __JsonReader
{
public static IObservable<System.Boolean> Read(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.Read());
}
public static IObservable<System.Nullable<System.Int32>> ReadAsInt32(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ReadAsInt32());
}
public static IObservable<System.String> ReadAsString(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ReadAsString());
}
public static IObservable<System.Byte[]> ReadAsBytes(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ReadAsBytes());
}
public static IObservable<System.Nullable<System.Double>> ReadAsDouble(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ReadAsDouble());
}
public static IObservable<System.Nullable<System.Boolean>> ReadAsBoolean(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ReadAsBoolean());
}
public static IObservable<System.Nullable<System.Decimal>> ReadAsDecimal(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ReadAsDecimal());
}
public static IObservable<System.Nullable<System.DateTime>> ReadAsDateTime(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ReadAsDateTime());
}
public static IObservable<System.Nullable<System.DateTimeOffset>> ReadAsDateTimeOffset(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ReadAsDateTimeOffset());
}
public static IObservable<System.Reactive.Unit> Skip(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Do(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.Skip()).ToUnit();
}
public static IObservable<System.Reactive.Unit> Close(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Do(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.Close()).ToUnit();
}
public static IObservable<System.Boolean> get_CloseInput(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.CloseInput);
}
public static IObservable<System.Boolean> get_SupportMultipleContent(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.SupportMultipleContent);
}
public static IObservable<System.Char> get_QuoteChar(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.QuoteChar);
}
public static IObservable<Newtonsoft.Json.DateTimeZoneHandling> get_DateTimeZoneHandling(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.DateTimeZoneHandling);
}
public static IObservable<Newtonsoft.Json.DateParseHandling> get_DateParseHandling(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.DateParseHandling);
}
public static IObservable<Newtonsoft.Json.FloatParseHandling> get_FloatParseHandling(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.FloatParseHandling);
}
public static IObservable<System.String> get_DateFormatString(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.DateFormatString);
}
public static IObservable<System.Nullable<System.Int32>> get_MaxDepth(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.MaxDepth);
}
public static IObservable<Newtonsoft.Json.JsonToken> get_TokenType(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.TokenType);
}
public static IObservable<System.Object> get_Value(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.Value);
}
public static IObservable<System.Type> get_ValueType(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.ValueType);
}
public static IObservable<System.Int32> get_Depth(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.Depth);
}
public static IObservable<System.String> get_Path(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.Path);
}
public static IObservable<System.Globalization.CultureInfo> get_Culture(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue)
{
return Observable.Select(JsonReaderValue, (JsonReaderValueLambda) => JsonReaderValueLambda.Culture);
}
public static IObservable<System.Reactive.Unit> set_CloseInput(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue, IObservable<System.Boolean> value)
{
return ObservableExt.ZipExecute(JsonReaderValue, value, (JsonReaderValueLambda, valueLambda) => JsonReaderValueLambda.CloseInput = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_SupportMultipleContent(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue, IObservable<System.Boolean> value)
{
return ObservableExt.ZipExecute(JsonReaderValue, value, (JsonReaderValueLambda, valueLambda) => JsonReaderValueLambda.SupportMultipleContent = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_DateTimeZoneHandling(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue, IObservable<Newtonsoft.Json.DateTimeZoneHandling> value)
{
return ObservableExt.ZipExecute(JsonReaderValue, value, (JsonReaderValueLambda, valueLambda) => JsonReaderValueLambda.DateTimeZoneHandling = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_DateParseHandling(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue, IObservable<Newtonsoft.Json.DateParseHandling> value)
{
return ObservableExt.ZipExecute(JsonReaderValue, value, (JsonReaderValueLambda, valueLambda) => JsonReaderValueLambda.DateParseHandling = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_FloatParseHandling(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue, IObservable<Newtonsoft.Json.FloatParseHandling> value)
{
return ObservableExt.ZipExecute(JsonReaderValue, value, (JsonReaderValueLambda, valueLambda) => JsonReaderValueLambda.FloatParseHandling = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_DateFormatString(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(JsonReaderValue, value, (JsonReaderValueLambda, valueLambda) => JsonReaderValueLambda.DateFormatString = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_MaxDepth(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue, IObservable<System.Nullable<System.Int32>> value)
{
return ObservableExt.ZipExecute(JsonReaderValue, value, (JsonReaderValueLambda, valueLambda) => JsonReaderValueLambda.MaxDepth = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Culture(this IObservable<Newtonsoft.Json.JsonReader> JsonReaderValue, IObservable<System.Globalization.CultureInfo> value)
{
return ObservableExt.ZipExecute(JsonReaderValue, value, (JsonReaderValueLambda, valueLambda) => JsonReaderValueLambda.Culture = valueLambda);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall.Graphics;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
#if WINDOWS_PHONE
using Microsoft.Phone.Info;
#endif
namespace FlatRedBall.Debugging
{
class CountedCategory
{
public string String;
public int Count;
public int Invisible;
public override string ToString()
{
return String;
}
}
public static class Debugger
{
#region Enums
public enum Corner
{
TopLeft,
TopRight,
BottomLeft,
BottomRight
}
#endregion
#region Fields
static Text mText;
static Layer mLayer;
static string MemoryInformation;
static double LastCalculationTime;
public static Corner TextCorner = Corner.TopLeft;
public static float TextRed = 1;
public static float TextGreen = 1;
public static float TextBlue = 1;
public static int NumberOfLinesInCommandLine = 5;
static List<string> mCommandLineOutput = new List<string>();
#if DEBUG
static RollingAverage mAllocationAverage = new RollingAverage(4);
static long mLastMemoryUse = -1;
#endif
#if WINDOWS_PHONE
static double mMemoryUpdateFrequency = 1;
#else
static double mMemoryUpdateFrequency = .25;
#endif
#endregion
#region Properties
public static double MemoryUpdateFrequency
{
get { return mMemoryUpdateFrequency; }
set { mMemoryUpdateFrequency = value; }
}
public static AutomaticDebuggingBehavior AutomaticDebuggingBehavior
{
get;
set;
}
#endregion
#region Constructor
static Debugger()
{
AutomaticDebuggingBehavior = new AutomaticDebuggingBehavior();
}
#endregion
#region Methods
static void CreateTextIfNecessary()
{
if (mText == null)
{
mText = TextManager.AddText("");
mLayer = SpriteManager.TopLayer;
TextManager.AddToLayer(mText, mLayer);
mText.AttachTo(SpriteManager.Camera, false);
mText.VerticalAlignment = VerticalAlignment.Top;
mText.AdjustPositionForPixelPerfectDrawing = true;
}
}
public static void DestroyText()
{
if (mText != null)
{
SpriteManager.RemoveLayer(mLayer);
TextManager.RemoveText(mText);
mLayer = null;
mText = null;
}
}
public static void ClearCommandLine()
{
mCommandLineOutput.Clear();
}
public static void CommandLineWrite(string stringToWrite)
{
mCommandLineOutput.Add(stringToWrite);
if (mCommandLineOutput.Count > NumberOfLinesInCommandLine)
{
mCommandLineOutput.RemoveAt(0);
}
}
public static void CommandLineWrite(object objectToWrite)
{
if (objectToWrite != null)
{
CommandLineWrite(objectToWrite.ToString());
}
else
{
CommandLineWrite("<null>");
}
}
public static void Write(string stringToWrite)
{
CreateTextIfNecessary();
mText.DisplayText = stringToWrite;
//position the text each frame in case of camera changes
AdjustTextPosition();
mText.Red = TextRed;
mText.Green = TextGreen;
mText.Blue = TextBlue;
mText.SetPixelPerfectScale(mLayer);
}
public static void Write(object objectToWrite)
{
if (objectToWrite == null)
{
Write("<NULL>");
}
else
{
Write(objectToWrite.ToString());
}
}
public static void WriteMemoryInformation()
{
if (TimeManager.SecondsSince(LastCalculationTime) > mMemoryUpdateFrequency)
{
MemoryInformation = ForceGetMemoryInformation();
}
Write(MemoryInformation);
}
public static string ForceGetMemoryInformation()
{
string memoryInformation;
long currentUsage;
#if WINDOWS_PHONE
currentUsage = (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
memoryInformation = DeviceExtendedProperties.GetValue("DeviceTotalMemory") + "\n" +
currentUsage + "\n" +
DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
#else
currentUsage = GC.GetTotalMemory(false);
memoryInformation = "Total Memory: " + currentUsage;
#endif
#if DEBUG
if (mLastMemoryUse >= 0)
{
long difference = currentUsage - mLastMemoryUse;
if (difference >= 0)
{
mAllocationAverage.AddValue((float)(difference / mMemoryUpdateFrequency));
}
}
memoryInformation += "\nAverage Growth per second: " +
mAllocationAverage.Average.ToString("0,000");
#endif
LastCalculationTime = TimeManager.CurrentTime;
#if DEBUG
mLastMemoryUse = currentUsage;
#endif
return memoryInformation;
}
public static void WriteAutomaticallyUpdatedObjectInformation()
{
string result = GetAutomaticallyUpdatedObjectInformation();
Write(result);
}
public static string GetAutomaticallyUpdatedObjectInformation()
{
StringBuilder stringBuilder = new StringBuilder();
int total = 0;
// SpriteManager
stringBuilder.AppendLine(SpriteManager.ManagedPositionedObjects.Count + " PositionedObjects");
total += SpriteManager.ManagedPositionedObjects.Count;
stringBuilder.AppendLine(SpriteManager.AutomaticallyUpdatedSprites.Count + " Sprites");
stringBuilder.AppendLine(" " + SpriteManager.ParticleCount + " Particles");
stringBuilder.AppendLine(" " + (SpriteManager.AutomaticallyUpdatedSprites.Count - SpriteManager.ParticleCount) + " Non-Particles");
total += SpriteManager.AutomaticallyUpdatedSprites.Count;
stringBuilder.AppendLine(SpriteManager.SpriteFrames.Count + " SpriteFrames");
total += SpriteManager.SpriteFrames.Count;
stringBuilder.AppendLine(SpriteManager.Cameras.Count + " Cameras");
total += SpriteManager.Cameras.Count;
// ShapeManager
stringBuilder.AppendLine(ShapeManager.AutomaticallyUpdatedShapes.Count + " Shapes");
total += ShapeManager.AutomaticallyUpdatedShapes.Count;
// TextManager
stringBuilder.AppendLine(TextManager.AutomaticallyUpdatedTexts.Count + " Texts");
total += TextManager.AutomaticallyUpdatedTexts.Count;
stringBuilder.AppendLine("---------------");
stringBuilder.AppendLine(total + " Total");
string result = stringBuilder.ToString();
return result;
}
public static void WriteAutomaticallyUpdatedSpriteFrameBreakdown()
{
string result =
GetAutomaticallyUpdatedBreakdownFromList<FlatRedBall.ManagedSpriteGroups.SpriteFrame>(SpriteManager.SpriteFrames);
Write(result);
}
public static void WriteAutomaticallyUpdatedShapeBreakdown()
{
var result =
GetShapeBreakdown();
Write(result);
}
public static void WriteAutomaticallyUpdatedSpriteBreakdown()
{
string result = GetAutomaticallyUpdatedSpriteBreakdown();
Write(result);
}
public static string GetAutomaticallyUpdatedSpriteBreakdown()
{
return GetAutomaticallyUpdatedBreakdownFromList<Sprite>(SpriteManager.AutomaticallyUpdatedSprites);
}
public static string GetAutomaticallyUpdatedBreakdownFromList<T>(IEnumerable<T> list) where T : PositionedObject
{
Dictionary<string, CountedCategory> typeDictionary = new Dictionary<string, CountedCategory>();
bool isIVisible = false;
if (list.Count() != 0)
{
isIVisible = list.First() is IVisible;
}
foreach(var atI in list)
{
string typeName = "Unparented";
if (typeof(T) != atI.GetType())
{
typeName = atI.GetType().Name;
}
else if (atI.Parent != null)
{
typeName = atI.Parent.GetType().Name;
}
if (typeDictionary.ContainsKey(typeName) == false)
{
var toAdd = new CountedCategory();
toAdd.String = typeName;
typeDictionary.Add(typeName, toAdd);
}
typeDictionary[typeName].Count++;
if (isIVisible && !((IVisible)atI).AbsoluteVisible)
{
typeDictionary[typeName].Invisible++;
}
}
string toReturn = "Total: " + list.Count() + " " + typeof(T).Name + "s\n" +
GetFilledStringBuilderWithNumberedTypes(typeDictionary).ToString();
if (list.Count() == 0)
{
toReturn = "No automatically updated " + typeof(T).Name + "s";
}
return toReturn;
}
public static void WritePositionedObjectBreakdown()
{
string result = GetPositionedObjectBreakdown();
Write(result);
}
public static string GetPositionedObjectBreakdown()
{
Dictionary<string, CountedCategory> typeDictionary = new Dictionary<string, CountedCategory>();
int count = SpriteManager.ManagedPositionedObjects.Count;
for (int i = 0; i < count; i++)
{
var atI = SpriteManager.ManagedPositionedObjects[i];
Type type = atI.GetType();
if (typeDictionary.ContainsKey(type.Name) == false)
{
var countedCategory = new CountedCategory();
countedCategory.String = type.Name;
typeDictionary.Add(type.Name, countedCategory);
}
typeDictionary[type.Name].Count++;
}
StringBuilder stringBuilder = GetFilledStringBuilderWithNumberedTypes(typeDictionary);
string toReturn = "Total: " + count + "\n" + stringBuilder.ToString();
if (count == 0)
{
toReturn = "No automatically updated PositionedObjects";
}
return toReturn;
}
public static string GetShapeBreakdown()
{
Dictionary<string, CountedCategory> typeDictionary = new Dictionary<string, CountedCategory>();
foreach(PositionedObject shape in ShapeManager.AutomaticallyUpdatedShapes)
{
var parent = shape.Parent;
string parentType = "<null>";
if(parent != null)
{
parentType = parent.GetType().Name;
}
if (typeDictionary.ContainsKey(parentType) == false)
{
var countedCategory = new CountedCategory();
countedCategory.String = parentType;
typeDictionary.Add(parentType, countedCategory);
}
typeDictionary[parentType].Count++;
}
StringBuilder stringBuilder = GetFilledStringBuilderWithNumberedTypes(typeDictionary);
var count = ShapeManager.AutomaticallyUpdatedShapes.Count;
string toReturn = "Total: " + count + "\n" + stringBuilder.ToString();
if (count == 0)
{
toReturn = "No automatically updated Shapes";
}
return toReturn;
}
private static StringBuilder GetFilledStringBuilderWithNumberedTypes(Dictionary<string, CountedCategory> typeDictionary)
{
List<CountedCategory> listOfItems = new List<CountedCategory>();
foreach (var kvp in typeDictionary)
{
listOfItems.Add(kvp.Value);
}
listOfItems.Sort((first, second) => second.Count.CompareTo(first.Count));
StringBuilder stringBuilder = new StringBuilder();
foreach (var item in listOfItems)
{
if (item.Invisible != 0)
{
string whatToAdd = item.Count + " (" + item.Invisible + " invisible)" + " " + item.String;
stringBuilder.AppendLine(whatToAdd);
}
else
{
stringBuilder.AppendLine(item.Count + " " + item.String);
}
}
return stringBuilder;
}
public static void Update()
{
if (mText != null)
{
mText.DisplayText = "";
mText.Red = TextRed;
mText.Green = TextGreen;
mText.Blue = TextBlue;
if (mCommandLineOutput.Count != 0)
{
for (int i = 0; i < mCommandLineOutput.Count; i++)
{
mText.DisplayText += mCommandLineOutput[i] + '\n';
}
}
}
else if(mCommandLineOutput.Count != 0)
{
Write("Command Line...");
}
}
internal static void UpdateDependencies()
{
if (mText != null)
{
AdjustTextPosition();
mText.UpdateDependencies(TimeManager.CurrentTime);
mText.SetPixelPerfectScale(mLayer);
bool orthogonal = true;
if (mLayer.LayerCameraSettings != null)
{
orthogonal = mLayer.LayerCameraSettings.Orthogonal;
}
else
{
orthogonal = Camera.Main.Orthogonal;
}
mText.AdjustPositionForPixelPerfectDrawing = orthogonal;
}
}
private static void AdjustTextPosition()
{
switch(TextCorner)
{
case Corner.TopLeft:
mText.RelativeX = -SpriteManager.Camera.RelativeXEdgeAt(SpriteManager.Camera.Z -40) * .95f;// -15;
mText.RelativeY = SpriteManager.Camera.RelativeYEdgeAt(SpriteManager.Camera.Z - 40) * .95f;
mText.HorizontalAlignment = HorizontalAlignment.Left;
break;
case Corner.TopRight:
mText.RelativeX = SpriteManager.Camera.RelativeXEdgeAt(SpriteManager.Camera.Z -40) * .95f;// -15;
mText.RelativeY = SpriteManager.Camera.RelativeYEdgeAt(SpriteManager.Camera.Z - 40) * .95f;
mText.HorizontalAlignment = HorizontalAlignment.Right;
break;
case Corner.BottomLeft:
mText.RelativeX = -SpriteManager.Camera.RelativeXEdgeAt(SpriteManager.Camera.Z -40) * .95f;// -15;
mText.RelativeY = -SpriteManager.Camera.RelativeYEdgeAt(SpriteManager.Camera.Z - 40) * .95f +
NumberOfLinesInCommandLine * mText.NewLineDistance;
mText.HorizontalAlignment = HorizontalAlignment.Left;
break;
case Corner.BottomRight:
mText.RelativeX = SpriteManager.Camera.RelativeXEdgeAt(SpriteManager.Camera.Z - 40) * .95f;// -15;
mText.RelativeY = -SpriteManager.Camera.RelativeYEdgeAt(SpriteManager.Camera.Z - 40) * .95f +
NumberOfLinesInCommandLine * mText.NewLineDistance;
mText.HorizontalAlignment = HorizontalAlignment.Right;
break;
}
mText.RelativeZ = -40;
if (float.IsNaN(mText.RelativeX) || float.IsPositiveInfinity(mText.RelativeX) || float.IsNegativeInfinity(mText.RelativeX))
{
mText.RelativeX = 0;
}
if (float.IsNaN(mText.RelativeY) || float.IsPositiveInfinity(mText.RelativeY) || float.IsNegativeInfinity(mText.RelativeY))
{
mText.RelativeY = 0;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
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)
{
ProcessManager.ThrowIfRemoteMachine(machineName);
if (processName == null)
{
processName = string.Empty;
}
var reusableReader = new ReusableTextReader();
var processes = new List<Process>();
foreach (int pid in ProcessManager.EnumerateProcessIds())
{
Interop.procfs.ParsedStat parsedStat;
if (Interop.procfs.TryReadStatFile(pid, out parsedStat, reusableReader) &&
string.Equals(processName, parsedStat.comm, StringComparison.OrdinalIgnoreCase))
{
ProcessInfo processInfo = ProcessManager.CreateProcessInfo(parsedStat, reusableReader);
processes.Add(new Process(machineName, false, processInfo.ProcessId, processInfo));
}
}
return processes.ToArray();
}
/// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary>
public TimeSpan PrivilegedProcessorTime
{
get
{
return TicksToTimeSpan(GetStat().stime);
}
}
/// <summary>Gets the time the associated process was started.</summary>
internal DateTime StartTimeCore
{
get
{
return BootTimeToDateTime(TicksToTimeSpan(GetStat().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
{
Interop.procfs.ParsedStat stat = GetStat();
return TicksToTimeSpan(stat.utime + stat.stime);
}
}
/// <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 TicksToTimeSpan(GetStat().utime);
}
}
partial void EnsureHandleCountPopulated()
{
if (_processInfo.HandleCount <= 0 && _haveProcessId)
{
string path = Interop.procfs.GetFileDescriptorDirectoryPathForProcess(_processId);
if (Directory.Exists(path))
{
try
{
_processInfo.HandleCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;
}
catch (DirectoryNotFoundException) // Occurs when the process is deleted between the Exists check and the GetFiles call.
{
}
}
}
}
/// <summary>
/// Gets or sets which processors the threads in this process can be scheduled to run on.
/// </summary>
private unsafe IntPtr ProcessorAffinityCore
{
get
{
EnsureState(State.HaveId);
IntPtr set;
if (Interop.Sys.SchedGetAffinity(_processId, out set) != 0)
{
throw new Win32Exception(); // match Windows exception
}
return set;
}
set
{
EnsureState(State.HaveId);
if (Interop.Sys.SchedSetAffinity(_processId, ref value) != 0)
{
throw new Win32Exception(); // match Windows exception
}
}
}
/// <summary>
/// Make sure we have obtained the min and max working set limits.
/// </summary>
private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet)
{
minWorkingSet = IntPtr.Zero; // no defined limit available
ulong rsslim = GetStat().rsslim;
// rsslim is a ulong, but maxWorkingSet is an IntPtr, so we need to cap rsslim
// at the max size of IntPtr. This often happens when there is no configured
// rsslim other than ulong.MaxValue, which without these checks would show up
// as a maxWorkingSet == -1.
switch (IntPtr.Size)
{
case 4:
if (rsslim > int.MaxValue)
rsslim = int.MaxValue;
break;
case 8:
if (rsslim > long.MaxValue)
rsslim = long.MaxValue;
break;
}
maxWorkingSet = (IntPtr)rsslim;
}
/// <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)
{
// RLIMIT_RSS with setrlimit not supported on Linux > 2.4.30.
throw new PlatformNotSupportedException();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Gets the path to the current executable, or null if it could not be retrieved.</summary>
private static string GetExePath()
{
// Determine the maximum size of a path
int maxPath = Interop.Sys.MaxPath;
// Start small with a buffer allocation, and grow only up to the max path
for (int pathLen = 256; pathLen < maxPath; pathLen *= 2)
{
// Read from procfs the symbolic link to this process' executable
byte[] buffer = new byte[pathLen + 1]; // +1 for null termination
int resultLength = Interop.Sys.ReadLink(Interop.procfs.SelfExeFilePath, buffer, pathLen);
// If we got one, null terminate it (readlink doesn't do this) and return the string
if (resultLength > 0)
{
buffer[resultLength] = (byte)'\0';
return Encoding.UTF8.GetString(buffer, 0, resultLength);
}
// If the buffer was too small, loop around again and try with a larger buffer.
// Otherwise, bail.
if (resultLength == 0 || Interop.Sys.GetLastError() != Interop.Error.ENAMETOOLONG)
{
break;
}
}
// Could not get a path
return null;
}
// ----------------------------------
// ---- Unix PAL layer ends here ----
// ----------------------------------
/// <summary>Reads the stats information for this process from the procfs file system.</summary>
private Interop.procfs.ParsedStat GetStat()
{
EnsureState(State.HaveId);
Interop.procfs.ParsedStat stat;
if (!Interop.procfs.TryReadStatFile(_processId, out stat, new ReusableTextReader()))
{
throw new Win32Exception(SR.ProcessInformationUnavailable);
}
return stat;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using Internal.Runtime.Augments;
using System.Diagnostics;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Hooks for System.Private.Interop.dll code to access internal functionality in System.Private.CoreLib.dll.
///
/// Methods added to InteropExtensions should also be added to the System.Private.CoreLib.InteropServices contract
/// in order to be accessible from System.Private.Interop.dll.
/// </summary>
[CLSCompliant(false)]
public static class InteropExtensions
{
// Converts a managed DateTime to native OLE datetime
// Used by MCG marshalling code
public static double ToNativeOleDate(DateTime dateTime)
{
return dateTime.ToOADate();
}
// Converts native OLE datetime to managed DateTime
// Used by MCG marshalling code
public static DateTime FromNativeOleDate(double nativeOleDate)
{
return new DateTime(DateTime.DoubleDateToTicks(nativeOleDate));
}
// Used by MCG's SafeHandle marshalling code to initialize a handle
public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle)
{
safeHandle.InitializeHandle(win32Handle);
}
// Used for methods in System.Private.Interop.dll that need to work from offsets on boxed structs
public static unsafe void PinObjectAndCall(Object obj, Action<IntPtr> del)
{
fixed (IntPtr* pEEType = &obj.m_pEEType)
{
del((IntPtr)pEEType);
}
}
public static int GetElementSize(this Array array)
{
return array.EETypePtr.ComponentSize;
}
internal static bool MightBeBlittable(this EETypePtr eeType)
{
//
// This is used as the approximate implementation of MethodTable::IsBlittable(). It will err in the direction of declaring
// things blittable since it is used for argument validation only.
//
return !eeType.HasPointers;
}
public static bool IsBlittable(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().MightBeBlittable();
}
public static bool IsBlittable(this Object obj)
{
return obj.EETypePtr.MightBeBlittable();
}
public static bool IsGenericType(this RuntimeTypeHandle handle)
{
EETypePtr eeType = handle.ToEETypePtr();
return eeType.IsGeneric;
}
public static bool IsGenericTypeDefinition(this RuntimeTypeHandle handle)
{
EETypePtr eeType = handle.ToEETypePtr();
return eeType.IsGenericTypeDefinition;
}
public static unsafe int GetGenericArgumentCount(this RuntimeTypeHandle genericTypeDefinitionHandle)
{
Debug.Assert(IsGenericTypeDefinition(genericTypeDefinitionHandle));
return genericTypeDefinitionHandle.ToEETypePtr().ToPointer()->GenericArgumentCount;
}
//TODO:Remove Delegate.GetNativeFunctionPointer
public static IntPtr GetNativeFunctionPointer(this Delegate del)
{
return del.GetNativeFunctionPointer();
}
public static IntPtr GetFunctionPointer(this Delegate del, out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate)
{
return del.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out bool _, out bool _);
}
//
// Returns the raw function pointer for a open static delegate - if the function has a jump stub
// it returns the jump target. Therefore the function pointer returned
// by two delegates may NOT be unique
//
public static IntPtr GetRawFunctionPointerForOpenStaticDelegate(this Delegate del)
{
//If it is not open static then return IntPtr.Zero
if (!del.IsOpenStatic)
return IntPtr.Zero;
RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate;
IntPtr funcPtr = del.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out bool _, out bool _);
// if the function pointer points to a jump stub return the target
return RuntimeImports.RhGetJmpStubCodeTarget(funcPtr);
}
public static IntPtr GetRawValue(this RuntimeTypeHandle handle)
{
return handle.RawValue;
}
/// <summary>
/// Comparing RuntimeTypeHandle with an object's RuntimeTypeHandle, avoiding going through expensive Object.GetType().TypeHandle path
/// </summary>
public static bool IsOfType(this Object obj, RuntimeTypeHandle handle)
{
RuntimeTypeHandle objType = new RuntimeTypeHandle(obj.EETypePtr);
return handle.Equals(objType);
}
public static bool IsNull(this RuntimeTypeHandle handle)
{
return handle.IsNull;
}
public static Type GetTypeFromHandle(IntPtr typeHandle)
{
return Type.GetTypeFromHandle(new RuntimeTypeHandle(new EETypePtr(typeHandle)));
}
public static Type GetTypeFromHandle(RuntimeTypeHandle typeHandle)
{
return Type.GetTypeFromHandle(typeHandle);
}
public static int GetValueTypeSize(this RuntimeTypeHandle handle)
{
return (int)handle.ToEETypePtr().ValueTypeSize;
}
public static bool IsValueType(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsValueType;
}
public static bool IsClass(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsDefType && !handle.ToEETypePtr().IsInterface && !handle.ToEETypePtr().IsValueType && !handle.IsDelegate();
}
public static bool IsEnum(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsEnum;
}
public static bool IsInterface(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsInterface;
}
public static bool IsPrimitive(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsPrimitive;
}
public static bool IsDelegate(this RuntimeTypeHandle handle)
{
return InteropExtensions.AreTypesAssignable(handle, typeof(MulticastDelegate).TypeHandle) ||
InteropExtensions.AreTypesAssignable(handle, typeof(Delegate).TypeHandle);
}
public static bool AreTypesAssignable(RuntimeTypeHandle sourceType, RuntimeTypeHandle targetType)
{
return RuntimeImports.AreTypesAssignable(sourceType.ToEETypePtr(), targetType.ToEETypePtr());
}
public static unsafe void Memcpy(IntPtr destination, IntPtr source, int bytesToCopy)
{
Buffer.Memmove((byte*)destination, (byte*)source, (uint)bytesToCopy);
}
public static bool RuntimeRegisterGcCalloutForGCStart(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.StartCollection, pCalloutMethod);
}
public static bool RuntimeRegisterGcCalloutForGCEnd(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.EndCollection, pCalloutMethod);
}
public static bool RuntimeRegisterGcCalloutForAfterMarkPhase(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.AfterMarkPhase, pCalloutMethod);
}
public static bool RuntimeRegisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter)
{
return RuntimeImports.RhRegisterRefCountedHandleCallback(pCalloutMethod, pTypeFilter.ToEETypePtr());
}
public static void RuntimeUnregisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter)
{
RuntimeImports.RhUnregisterRefCountedHandleCallback(pCalloutMethod, pTypeFilter.ToEETypePtr());
}
/// <summary>
/// The type of a RefCounted handle
/// A ref-counted handle is a handle that acts as strong if the callback returns true, and acts as
/// weak handle if the callback returns false, which is perfect for controlling lifetime of a CCW
/// </summary>
internal const int RefCountedHandleType = 5;
public static IntPtr RuntimeHandleAllocRefCounted(Object value)
{
return RuntimeImports.RhHandleAlloc(value, (GCHandleType)RefCountedHandleType);
}
public static void RuntimeHandleSet(IntPtr handle, Object value)
{
RuntimeImports.RhHandleSet(handle, value);
}
public static void RuntimeHandleFree(IntPtr handle)
{
RuntimeImports.RhHandleFree(handle);
}
public static IntPtr RuntimeHandleAllocDependent(object primary, object secondary)
{
return RuntimeImports.RhHandleAllocDependent(primary, secondary);
}
public static bool RuntimeIsPromoted(object obj)
{
return RuntimeImports.RhIsPromoted(obj);
}
public static void RuntimeHandleSetDependentSecondary(IntPtr handle, Object secondary)
{
RuntimeImports.RhHandleSetDependentSecondary(handle, secondary);
}
public static T UncheckedCast<T>(object obj) where T : class
{
return Unsafe.As<T>(obj);
}
public static bool IsArray(RuntimeTypeHandle type)
{
return type.ToEETypePtr().IsArray;
}
public static RuntimeTypeHandle GetArrayElementType(RuntimeTypeHandle arrayType)
{
return new RuntimeTypeHandle(arrayType.ToEETypePtr().ArrayElementType);
}
/// <summary>
/// Whether the type is a single dimension zero lower bound array
/// </summary>
/// <param name="type">specified type</param>
/// <returns>true iff it is a single dimension zeo lower bound array</returns>
public static bool IsSzArray(RuntimeTypeHandle type)
{
return type.ToEETypePtr().IsSzArray;
}
public static RuntimeTypeHandle GetTypeHandle(this object target)
{
return new RuntimeTypeHandle(target.EETypePtr);
}
public static bool IsInstanceOf(object obj, RuntimeTypeHandle typeHandle)
{
return (null != RuntimeImports.IsInstanceOf(obj, typeHandle.ToEETypePtr()));
}
public static bool IsInstanceOfClass(object obj, RuntimeTypeHandle classTypeHandle)
{
return (null != RuntimeImports.IsInstanceOfClass(obj, classTypeHandle.ToEETypePtr()));
}
public static bool IsInstanceOfInterface(object obj, RuntimeTypeHandle interfaceTypeHandle)
{
return (null != RuntimeImports.IsInstanceOfInterface(obj, interfaceTypeHandle.ToEETypePtr()));
}
public static bool GuidEquals(ref Guid left, ref Guid right)
{
return left.Equals(ref right);
}
public static bool ComparerEquals<T>(T left, T right)
{
return EqualOnlyComparer<T>.Equals(left, right);
}
public static object RuntimeNewObject(RuntimeTypeHandle typeHnd)
{
return RuntimeImports.RhNewObject(typeHnd.ToEETypePtr());
}
public static unsafe void UnsafeCopyTo(this System.Text.StringBuilder stringBuilder, char* destination)
{
stringBuilder.UnsafeCopyTo(destination);
}
public static unsafe void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char* newBuffer)
{
stringBuilder.ReplaceBuffer(newBuffer);
}
public static void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char[] newBuffer)
{
stringBuilder.ReplaceBuffer(newBuffer);
}
public static char[] GetBuffer(this System.Text.StringBuilder stringBuilder, out int len)
{
return stringBuilder.GetBuffer(out len);
}
public static IntPtr RuntimeHandleAllocVariable(Object value, uint type)
{
return RuntimeImports.RhHandleAllocVariable(value, type);
}
public static uint RuntimeHandleGetVariableType(IntPtr handle)
{
return RuntimeImports.RhHandleGetVariableType(handle);
}
public static void RuntimeHandleSetVariableType(IntPtr handle, uint type)
{
RuntimeImports.RhHandleSetVariableType(handle, type);
}
public static uint RuntimeHandleCompareExchangeVariableType(IntPtr handle, uint oldType, uint newType)
{
return RuntimeImports.RhHandleCompareExchangeVariableType(handle, oldType, newType);
}
public static void SetExceptionErrorCode(Exception exception, int hr)
{
exception.SetErrorCode(hr);
}
public static void SetExceptionMessage(Exception exception, string message)
{
exception.SetMessage(message);
}
public static Exception CreateDataMisalignedException(string message)
{
return new DataMisalignedException(message);
}
public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isVirtual, bool isOpen)
{
return Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic, isOpen);
}
public enum VariableHandleType
{
WeakShort = 0x00000100,
WeakLong = 0x00000200,
Strong = 0x00000400,
Pinned = 0x00000800,
}
public static void AddExceptionDataForRestrictedErrorInfo(Exception ex, string restrictedError, string restrictedErrorReference, string restrictedCapabilitySid, object restrictedErrorObject)
{
ex.AddExceptionDataForRestrictedErrorInfo(restrictedError, restrictedErrorReference, restrictedCapabilitySid, restrictedErrorObject);
}
public static bool TryGetRestrictedErrorObject(Exception ex, out object restrictedErrorObject)
{
return ex.TryGetRestrictedErrorObject(out restrictedErrorObject);
}
public static bool TryGetRestrictedErrorDetails(Exception ex, out string restrictedError, out string restrictedErrorReference, out string restrictedCapabilitySid)
{
return ex.TryGetRestrictedErrorDetails(out restrictedError, out restrictedErrorReference, out restrictedCapabilitySid);
}
public static TypeInitializationException CreateTypeInitializationException(string message)
{
return new TypeInitializationException(message);
}
public static unsafe IntPtr GetObjectID(object obj)
{
fixed (void* p = &obj.m_pEEType)
{
return (IntPtr)p;
}
}
public static bool RhpETWShouldWalkCom()
{
return RuntimeImports.RhpETWShouldWalkCom();
}
public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags)
{
RuntimeImports.RhpETWLogLiveCom(eventType, CCWHandle, objectID, typeRawValue, IUnknown, VTable, comRefCount, jupiterRefCount, flags);
}
public static bool SupportsReflection(this Type type)
{
return RuntimeAugments.Callbacks.SupportsReflection(type);
}
public static void SuppressReentrantWaits()
{
RuntimeThread.SuppressReentrantWaits();
}
public static void RestoreReentrantWaits()
{
RuntimeThread.RestoreReentrantWaits();
}
public static IntPtr GetCriticalHandle(CriticalHandle criticalHandle)
{
return criticalHandle.GetHandleInternal();
}
public static void SetCriticalHandle(CriticalHandle criticalHandle, IntPtr handle)
{
criticalHandle.SetHandleInternal(handle);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/25/2008 8:49:44 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Globalization;
namespace DotSpatial.Data
{
/// <summary>
/// Global has some basic methods that may be useful in lots of places.
/// TODO: This class needs to be removed and these methods relocated to easier to find places.
/// </summary>
public static class Global
{
/// <summary>
/// Converts a double numeric value into the appropriate T data type using a ChangeType process.
/// </summary>
/// <typeparam name="T">The numeric output type created from the double value.</typeparam>
/// <param name="value">The double value to retrieve the equivalent numeric value for.</param>
/// <returns>A variable of type T with the value of the value parameter.</returns>
public static T Convert<T>(double value)
{
return (T)System.Convert.ChangeType(value, typeof(T));
}
/// <summary>
/// This involves boxing and unboxing as well as a convert to double, but IConvertible was
/// not CLS Compliant, so we were always getting warnings about it. Ted was trying to make
/// all the code CLS Compliant to remove warnings.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static double ToDouble<U>(U value)
{
if (typeof(U) == typeof(byte)) return System.Convert.ToDouble((byte)(object)value);
if (typeof(U) == typeof(short)) return System.Convert.ToDouble((short)(object)value);
if (typeof(U) == typeof(int)) return System.Convert.ToDouble((int)(object)value);
if (typeof(U) == typeof(long)) return System.Convert.ToDouble((long)(object)value);
if (typeof(U) == typeof(float)) return System.Convert.ToDouble((float)(object)value);
if (typeof(U) == typeof(double)) return (double)(object)value;
if (typeof(U) == typeof(ushort)) return System.Convert.ToDouble((ushort)(object)value);
if (typeof(U) == typeof(uint)) return System.Convert.ToDouble((uint)(object)value);
if (typeof(U) == typeof(ulong)) return System.Convert.ToDouble((ulong)(object)value);
return 0;
}
/// <summary>
/// For numeric types, this will return the maximum value.
/// </summary>
/// <typeparam name="T">The type of the numeric range to find the maximum for.</typeparam>
/// <returns>The maximum value for the numeric type specified by T.</returns>
public static T MaximumValue<T>()
{
T value = default(T);
if (value is byte)
{
return SafeCastTo<T>(byte.MaxValue);
}
if (value is short)
{
return SafeCastTo<T>(short.MaxValue);
}
if (value is int)
{
return SafeCastTo<T>(int.MaxValue);
}
if (value is long)
{
return SafeCastTo<T>(long.MaxValue);
}
if (value is float)
{
return SafeCastTo<T>(float.MaxValue);
}
if (value is double)
{
return SafeCastTo<T>(double.MaxValue);
}
if (value is UInt16)
{
return SafeCastTo<T>(UInt16.MaxValue);
}
if (value is UInt32)
{
return SafeCastTo<T>(UInt32.MaxValue);
}
if (value is UInt64)
{
return SafeCastTo<T>(UInt64.MaxValue);
}
return default(T);
}
/// <summary>
/// For Numeric types, this will return the minimum value.
/// </summary>
/// <typeparam name="T">The type of the numeric range to return the minimum for.</typeparam>
/// <returns>The the minimum value possible for a numeric value of type T.</returns>
public static T MinimumValue<T>()
{
T value = default(T);
if (value is byte)
{
return SafeCastTo<T>(byte.MinValue);
}
if (value is short)
{
return SafeCastTo<T>(short.MinValue);
}
if (value is int)
{
return SafeCastTo<T>(int.MinValue);
}
if (value is long)
{
return SafeCastTo<T>(long.MinValue);
}
if (value is float)
{
return SafeCastTo<T>(float.MinValue);
}
if (value is double)
{
return SafeCastTo<T>(double.MinValue);
}
if (value is UInt16)
{
return SafeCastTo<T>(UInt16.MinValue);
}
if (value is UInt32)
{
return SafeCastTo<T>(UInt32.MinValue);
}
if (value is UInt64)
{
return SafeCastTo<T>(UInt64.MinValue);
}
return default(T);
}
/// <summary>
/// A Generic Safe Casting method that should simply exist as part of the core framework
/// </summary>
/// <typeparam name="T">The type of the member to attempt to cast to.</typeparam>
/// <param name="obj">The original object to attempt to System.Convert.</param>
/// <returns>An output variable of type T.</returns>
public static T SafeCastTo<T>(object obj)
{
if (obj == null)
{
return default(T);
}
if (!(obj is T))
{
return default(T);
}
return (T)obj;
}
/// <summary>
/// Uses the standard enum parsing, but returns it cast as the specified T parameter
/// </summary>
/// <typeparam name="T">The type of the enum to use</typeparam>
/// <param name="text">The string to parse into a copy of the enumeration</param>
/// <returns>an enumeration of the specified type</returns>
public static T ParseEnum<T>(string text)
{
return SafeCastTo<T>(Enum.Parse(typeof(T), text));
}
/// <summary>
/// This attempts to convert a value into a byte. If it fails, the byte will be 0.
/// </summary>
/// <param name="expression">The expression (like a string) to System.Convert.</param>
/// <returns>A byte that is 0 if the test fails.</returns>
public static byte GetByte(object expression)
{
byte retNum;
if (Byte.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum))
{
return retNum;
}
return 0;
}
/// <summary>
/// This attempts to convert a value into a double. If it fails, the double will be double.NaN.
/// </summary>
/// <param name="expression">The expression (like a string) to System.Convert.</param>
/// <returns>A double that is double.NAN if the test fails.</returns>
public static double GetDouble(object expression)
{
double retNum;
return Double.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum) ? retNum : double.NaN;
}
/// <summary>
/// This attempts to convert a value into a float. If it fails, the float will be 0.
/// </summary>
/// <param name="expression">The expression (like a string) to System.Convert.</param>
/// <returns>A float that is 0 if the test fails.</returns>
public static float GetFloat(object expression)
{
float retNum;
return Single.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum) ? retNum : 0F;
}
/// <summary>
/// This attempts to convert a value into an integer. If it fails, it returns 0.
/// </summary>
/// <param name="expression">The expression to test</param>
/// <returns>true if the value could be cast as a double, false otherwise</returns>
public static int GetInteger(object expression)
{
int retNum;
return Int32.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum) ? retNum : 0;
}
/// <summary>
/// This attempts to convert a value into a short. If it fails, it returns 0.
/// </summary>
/// <param name="expression">The expression (like a string) to System.Convert.</param>
/// <returns>A short that is 0 if the test fails.</returns>
public static double GetShort(object expression)
{
short retNum;
if (Int16.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum))
{
return retNum;
}
return 0;
}
/// <summary>
/// Gets the string form of the number using culture settings
/// </summary>
/// <param name="expression">The expression to obtain the string for</param>
/// <returns>A string</returns>
public static string GetString(object expression)
{
return System.Convert.ToString(expression, CulturePreferences.CultureInformation.NumberFormat);
}
/// <summary>
/// Tests an expression to see if it can be converted into a byte.
/// </summary>
/// <param name="expression">The expression to test</param>
/// <returns>true if the value could be cast as a double, false otherwise</returns>
public static bool IsByte(object expression)
{
byte retNum;
bool isNum = Byte.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum);
return isNum;
}
/// <summary>
/// Tests an expression to see if it can be converted into a double.
/// </summary>
/// <param name="expression">The expression to test</param>
/// <returns>true if the value could be cast as a double, false otherwise</returns>
public static bool IsDouble(object expression)
{
double retNum;
bool isNum = Double.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum);
return isNum;
}
/// <summary>
/// Tests an expression to see if it can be converted into a float.
/// </summary>
/// <param name="expression">The expression to test</param>
/// <returns>true if the value could be cast as a double, false otherwise</returns>
public static bool IsFloat(object expression)
{
float retNum;
bool isNum = Single.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum);
return isNum;
}
/// <summary>
/// Tests an expression to see if it can be converted into an integer.
/// </summary>
/// <param name="expression">The expression to test</param>
/// <returns>true if the value could be cast as an integer, false otherwise</returns>
public static bool IsInteger(object expression)
{
int retNum;
bool isNum = Int32.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum);
return isNum;
}
/// <summary>
/// Tests an expression to see if it can be converted into a short.
/// </summary>
/// <param name="expression">The expression to test</param>
/// <returns>true if the value could be cast as a double, false otherwise</returns>
public static bool IsShort(object expression)
{
short retNum;
bool isNum = Int16.TryParse(GetString(expression), NumberStyles.Any, CulturePreferences.CultureInformation.NumberFormat, out retNum);
return isNum;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class FlushAsyncCancellationTests : PipeTest
{
[Fact]
public void FlushAsyncCancellationDeadlock()
{
var cts = new CancellationTokenSource();
var cts2 = new CancellationTokenSource();
PipeWriter buffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
var e = new ManualResetEventSlim();
ValueTaskAwaiter<FlushResult> awaiter = buffer.FlushAsync(cts.Token).GetAwaiter();
awaiter.OnCompleted(
() => {
// We are on cancellation thread and need to wait untill another FlushAsync call
// takes pipe state lock
e.Wait();
// Make sure we had enough time to reach _cancellationTokenRegistration.Dispose
Thread.Sleep(100);
// Try to take pipe state lock
buffer.FlushAsync();
});
// Start a thread that would run cancellation calbacks
Task cancellationTask = Task.Run(() => cts.Cancel());
// Start a thread that would call FlushAsync with different token
// and block on _cancellationTokenRegistration.Dispose
Task blockingTask = Task.Run(
() => {
e.Set();
buffer.FlushAsync(cts2.Token);
});
bool completed = Task.WhenAll(cancellationTask, blockingTask).Wait(TimeSpan.FromSeconds(10));
Assert.True(completed);
}
[Fact]
public async Task FlushAsyncCancellationE2E()
{
var cts = new CancellationTokenSource();
var cancelled = false;
Func<Task> taskFunc = async () => {
try
{
Pipe.Writer.WriteEmpty(MaximumSizeHigh);
await Pipe.Writer.FlushAsync(cts.Token);
}
catch (OperationCanceledException)
{
cancelled = true;
await Pipe.Writer.FlushAsync();
}
};
Task task = taskFunc();
cts.Cancel();
ReadResult result = await Pipe.Reader.ReadAsync();
Assert.Equal(new byte[MaximumSizeHigh], result.Buffer.ToArray());
Pipe.Reader.AdvanceTo(result.Buffer.End);
await task;
Assert.True(cancelled);
}
[Fact]
public void FlushAsyncCompletedAfterPreCancellation()
{
PipeWriter writableBuffer = Pipe.Writer.WriteEmpty(1);
Pipe.Writer.CancelPendingFlush();
ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync();
Assert.True(flushAsync.IsCompleted);
FlushResult flushResult = flushAsync.GetAwaiter().GetResult();
Assert.True(flushResult.IsCanceled);
flushAsync = writableBuffer.FlushAsync();
Assert.True(flushAsync.IsCompleted);
}
[Fact]
public void FlushAsyncNotCompletedAfterCancellation()
{
var onCompletedCalled = false;
PipeWriter writableBuffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
ValueTaskAwaiter<FlushResult> awaitable = writableBuffer.FlushAsync().GetAwaiter();
Assert.False(awaitable.IsCompleted);
awaitable.OnCompleted(
() => {
onCompletedCalled = true;
Assert.True(awaitable.IsCompleted);
FlushResult flushResult = awaitable.GetResult();
Assert.True(flushResult.IsCanceled);
awaitable = writableBuffer.FlushAsync().GetAwaiter();
Assert.False(awaitable.IsCompleted);
});
Pipe.Writer.CancelPendingFlush();
Assert.True(onCompletedCalled);
}
[Fact]
public void FlushAsyncNotCompletedAfterCancellationTokenCanceled()
{
var onCompletedCalled = false;
var cts = new CancellationTokenSource();
PipeWriter writableBuffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
ValueTaskAwaiter<FlushResult> awaitable = writableBuffer.FlushAsync(cts.Token).GetAwaiter();
Assert.False(awaitable.IsCompleted);
awaitable.OnCompleted(
() => {
onCompletedCalled = true;
Assert.True(awaitable.IsCompleted);
Assert.Throws<OperationCanceledException>(() => awaitable.GetResult());
awaitable = writableBuffer.FlushAsync().GetAwaiter();
Assert.False(awaitable.IsCompleted);
});
cts.Cancel();
Assert.True(onCompletedCalled);
}
[Fact]
public void FlushAsyncReturnsCanceledIfCanceledBeforeFlush()
{
PipeWriter writableBuffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
Pipe.Writer.CancelPendingFlush();
ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync();
Assert.True(flushAsync.IsCompleted);
FlushResult flushResult = flushAsync.GetAwaiter().GetResult();
Assert.True(flushResult.IsCanceled);
}
[Fact]
public void FlushAsyncReturnsCanceledIfFlushCanceled()
{
PipeWriter writableBuffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync();
Assert.False(flushAsync.IsCompleted);
Pipe.Writer.CancelPendingFlush();
Assert.True(flushAsync.IsCompleted);
FlushResult flushResult = flushAsync.GetAwaiter().GetResult();
Assert.True(flushResult.IsCanceled);
}
[Fact]
public void FlushAsyncReturnsIsCancelOnCancelPendingFlushAfterGetResult()
{
PipeWriter writableBuffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
ValueTaskAwaiter<FlushResult> awaitable = writableBuffer.FlushAsync().GetAwaiter();
Assert.False(awaitable.IsCompleted);
awaitable.OnCompleted(() => { });
Pipe.Writer.CancelPendingFlush();
Pipe.Reader.AdvanceTo(Pipe.Reader.ReadAsync().GetAwaiter().GetResult().Buffer.End);
Assert.True(awaitable.IsCompleted);
FlushResult result = awaitable.GetResult();
Assert.True(result.IsCanceled);
}
[Fact]
public void FlushAsyncReturnsIsCancelOnCancelPendingFlushBeforeGetResult()
{
PipeWriter writableBuffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
ValueTaskAwaiter<FlushResult> awaitable = writableBuffer.FlushAsync().GetAwaiter();
Assert.False(awaitable.IsCompleted);
awaitable.OnCompleted(() => { });
Pipe.Reader.AdvanceTo(Pipe.Reader.ReadAsync().GetAwaiter().GetResult().Buffer.End);
Pipe.Writer.CancelPendingFlush();
Assert.True(awaitable.IsCompleted);
FlushResult result = awaitable.GetResult();
Assert.True(result.IsCanceled);
}
[Fact]
public void FlushAsyncThrowsIfPassedCanceledCancellationToken()
{
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
Assert.Throws<OperationCanceledException>(() => Pipe.Writer.FlushAsync(cancellationTokenSource.Token));
}
[Fact]
public async Task FlushAsyncWithNewCancellationTokenNotAffectedByPrevious()
{
var cancellationTokenSource1 = new CancellationTokenSource();
PipeWriter buffer = Pipe.Writer.WriteEmpty(10);
await buffer.FlushAsync(cancellationTokenSource1.Token);
cancellationTokenSource1.Cancel();
var cancellationTokenSource2 = new CancellationTokenSource();
buffer = Pipe.Writer.WriteEmpty(10);
// Verifying that ReadAsync does not throw
await buffer.FlushAsync(cancellationTokenSource2.Token);
}
[Fact]
public void GetResultThrowsIfFlushAsyncCanceledAfterOnCompleted()
{
var onCompletedCalled = false;
var cancellationTokenSource = new CancellationTokenSource();
PipeWriter buffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
ValueTaskAwaiter<FlushResult> awaiter = buffer.FlushAsync(cancellationTokenSource.Token).GetAwaiter();
awaiter.OnCompleted(
() => {
onCompletedCalled = true;
Assert.Throws<OperationCanceledException>(() => awaiter.GetResult());
});
bool awaiterIsCompleted = awaiter.IsCompleted;
cancellationTokenSource.Cancel();
Assert.False(awaiterIsCompleted);
Assert.True(onCompletedCalled);
}
[Fact]
public void GetResultThrowsIfFlushAsyncCanceledBeforeOnCompleted()
{
var onCompletedCalled = false;
var cancellationTokenSource = new CancellationTokenSource();
PipeWriter buffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
ValueTaskAwaiter<FlushResult> awaiter = buffer.FlushAsync(cancellationTokenSource.Token).GetAwaiter();
bool awaiterIsCompleted = awaiter.IsCompleted;
cancellationTokenSource.Cancel();
awaiter.OnCompleted(
() => {
onCompletedCalled = true;
Assert.Throws<OperationCanceledException>(() => awaiter.GetResult());
});
Assert.False(awaiterIsCompleted);
Assert.True(onCompletedCalled);
}
[Fact]
public void GetResultThrowsIfFlushAsyncTokenFiredAfterCancelPending()
{
var onCompletedCalled = false;
var cancellationTokenSource = new CancellationTokenSource();
PipeWriter buffer = Pipe.Writer.WriteEmpty(MaximumSizeHigh);
ValueTaskAwaiter<FlushResult> awaiter = buffer.FlushAsync(cancellationTokenSource.Token).GetAwaiter();
bool awaiterIsCompleted = awaiter.IsCompleted;
Pipe.Writer.CancelPendingFlush();
cancellationTokenSource.Cancel();
awaiter.OnCompleted(
() => {
onCompletedCalled = true;
Assert.Throws<OperationCanceledException>(() => awaiter.GetResult());
});
Assert.False(awaiterIsCompleted);
Assert.True(onCompletedCalled);
}
[Fact]
public async Task FlushAsyncThrowsIfPassedCanceledCancellationTokenAndPipeIsAbleToComplete()
{
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
// AsTask is important here, it validates that we are calling completion callback
// and not only setting IsCompleted flag
var task = Pipe.Reader.ReadAsync().AsTask();
await Assert.ThrowsAsync<OperationCanceledException>(async () => await Pipe.Writer.FlushAsync(cancellationTokenSource.Token));
Pipe.Writer.Complete();
Assert.True(task.IsCompleted);
Assert.True(task.Result.IsCompleted);
}
[Fact]
public async Task ReadAsyncReturnsDataAfterItWasWrittenDuringCancelledRead()
{
ValueTask<ReadResult> readTask = Pipe.Reader.ReadAsync();
ValueTaskAwaiter<ReadResult> awaiter = readTask.GetAwaiter();
ReadResult result = default;
awaiter.OnCompleted(
() =>
{
Pipe.Writer.WriteAsync(new byte[] { 1 }).AsTask().Wait();
result = awaiter.GetResult();
});
Pipe.Reader.CancelPendingRead();
Assert.True(result.IsCanceled);
result = await Pipe.Reader.ReadAsync();
Assert.False(result.IsCanceled);
Assert.Equal(new byte[] { 1 }, result.Buffer.ToArray());
}
}
public static class TestWriterExtensions
{
public static PipeWriter WriteEmpty(this PipeWriter writer, int count)
{
writer.GetSpan(count).Slice(0, count).Fill(0);
writer.Advance(count);
return writer;
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using Xunit;
namespace Moq.Tests
{
public class CallbacksFixture
{
[Fact]
public void ExecutesCallbackWhenVoidMethodIsCalled()
{
var mock = new Mock<IFoo>();
bool called = false;
mock.Setup(x => x.Submit()).Callback(() => called = true);
mock.Object.Submit();
Assert.True(called);
}
[Fact]
public void ExecutesCallbackWhenNonVoidMethodIsCalled()
{
var mock = new Mock<IFoo>();
bool called = false;
mock.Setup(x => x.Execute("ping")).Callback(() => called = true).Returns("ack");
Assert.Equal("ack", mock.Object.Execute("ping"));
Assert.True(called);
}
[Fact]
public void CallbackCalledWithoutArgumentsForMethodCallWithArguments()
{
var mock = new Mock<IFoo>();
bool called = false;
mock.Setup(x => x.Submit(It.IsAny<string>())).Callback(() => called = true);
mock.Object.Submit("blah");
Assert.True(called);
}
[Fact]
public void FriendlyErrorWhenCallbackArgumentCountNotMatch()
{
var mock = new Mock<IFoo>();
Assert.Throws<ArgumentException>(() =>
mock.Setup(x => x.Submit(It.IsAny<string>()))
.Callback((string s1, string s2) => System.Console.WriteLine(s1 + s2)));
}
[Fact]
public void CallbackCalledWithOneArgument()
{
var mock = new Mock<IFoo>();
string callbackArg = null;
mock.Setup(x => x.Submit(It.IsAny<string>())).Callback((string s) => callbackArg = s);
mock.Object.Submit("blah");
Assert.Equal("blah", callbackArg);
}
[Fact]
public void CallbackCalledWithTwoArguments()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2) => { callbackArg1 = s1; callbackArg2 = s2; });
mock.Object.Submit("blah1", "blah2");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
}
[Fact]
public void CallbackCalledWithThreeArguments()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; });
mock.Object.Submit("blah1", "blah2", "blah3");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
}
[Fact]
public void CallbackCalledWithFourArguments()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; });
mock.Object.Submit("blah1", "blah2", "blah3", "blah4");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
}
[Fact]
public void CallbackCalledWithFiveArguments()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
string callbackArg5 = null;
mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4, string s5) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; });
mock.Object.Submit("blah1", "blah2", "blah3", "blah4", "blah5");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
Assert.Equal("blah5", callbackArg5);
}
[Fact]
public void CallbackCalledWithSixArguments()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
string callbackArg5 = null;
string callbackArg6 = null;
mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4, string s5, string s6) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; });
mock.Object.Submit("blah1", "blah2", "blah3", "blah4", "blah5", "blah6");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
Assert.Equal("blah5", callbackArg5);
Assert.Equal("blah6", callbackArg6);
}
[Fact]
public void CallbackCalledWithSevenArguments()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
string callbackArg5 = null;
string callbackArg6 = null;
string callbackArg7 = null;
mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4, string s5, string s6, string s7) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; callbackArg7 = s7; });
mock.Object.Submit("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
Assert.Equal("blah5", callbackArg5);
Assert.Equal("blah6", callbackArg6);
Assert.Equal("blah7", callbackArg7);
}
[Fact]
public void CallbackCalledWithEightArguments()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
string callbackArg5 = null;
string callbackArg6 = null;
string callbackArg7 = null;
string callbackArg8 = null;
mock.Setup(x => x.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4, string s5, string s6, string s7, string s8) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; callbackArg7 = s7; callbackArg8 = s8; });
mock.Object.Submit("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7", "blah8");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
Assert.Equal("blah5", callbackArg5);
Assert.Equal("blah6", callbackArg6);
Assert.Equal("blah7", callbackArg7);
Assert.Equal("blah8", callbackArg8);
}
[Fact]
public void CallbackCalledWithOneArgumentForNonVoidMethod()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
mock.Setup(x => x.Execute(It.IsAny<string>()))
.Callback((string s1) => callbackArg1 = s1)
.Returns("foo");
mock.Object.Execute("blah1");
Assert.Equal("blah1", callbackArg1);
}
[Fact]
public void CallbackCalledWithTwoArgumentsForNonVoidMethod()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2) => { callbackArg1 = s1; callbackArg2 = s2; })
.Returns("foo");
mock.Object.Execute("blah1", "blah2");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
}
[Fact]
public void CallbackCalledWithThreeArgumentsForNonVoidMethod()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; })
.Returns("foo");
mock.Object.Execute("blah1", "blah2", "blah3");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
}
[Fact]
public void CallbackCalledWithFourArgumentsForNonVoidMethod()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; })
.Returns("foo");
mock.Object.Execute("blah1", "blah2", "blah3", "blah4");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
}
[Fact]
public void CallbackCalledWithFiveArgumentsForNonVoidMethod()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
string callbackArg5 = null;
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4, string s5) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; })
.Returns("foo");
mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
Assert.Equal("blah5", callbackArg5);
}
[Fact]
public void CallbackCalledWithSixArgumentsForNonVoidMethod()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
string callbackArg5 = null;
string callbackArg6 = null;
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4, string s5, string s6) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; })
.Returns("foo");
mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
Assert.Equal("blah5", callbackArg5);
Assert.Equal("blah6", callbackArg6);
}
[Fact]
public void CallbackCalledWithSevenArgumentsForNonVoidMethod()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
string callbackArg5 = null;
string callbackArg6 = null;
string callbackArg7 = null;
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4, string s5, string s6, string s7) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; callbackArg7 = s7; })
.Returns("foo");
mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
Assert.Equal("blah5", callbackArg5);
Assert.Equal("blah6", callbackArg6);
Assert.Equal("blah7", callbackArg7);
}
[Fact]
public void CallbackCalledWithEightArgumentsForNonVoidMethod()
{
var mock = new Mock<IFoo>();
string callbackArg1 = null;
string callbackArg2 = null;
string callbackArg3 = null;
string callbackArg4 = null;
string callbackArg5 = null;
string callbackArg6 = null;
string callbackArg7 = null;
string callbackArg8 = null;
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((string s1, string s2, string s3, string s4, string s5, string s6, string s7, string s8) => { callbackArg1 = s1; callbackArg2 = s2; callbackArg3 = s3; callbackArg4 = s4; callbackArg5 = s5; callbackArg6 = s6; callbackArg7 = s7; callbackArg8 = s8; })
.Returns("foo");
mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7", "blah8");
Assert.Equal("blah1", callbackArg1);
Assert.Equal("blah2", callbackArg2);
Assert.Equal("blah3", callbackArg3);
Assert.Equal("blah4", callbackArg4);
Assert.Equal("blah5", callbackArg5);
Assert.Equal("blah6", callbackArg6);
Assert.Equal("blah7", callbackArg7);
Assert.Equal("blah8", callbackArg8);
}
[Fact]
public void CallbackCalledAfterReturnsCall()
{
var mock = new Mock<IFoo>();
bool returnsCalled = false;
bool beforeCalled = false;
bool afterCalled = false;
mock.Setup(foo => foo.Execute("ping"))
.Callback(() => { Assert.False(returnsCalled); beforeCalled = true; })
.Returns(() => { returnsCalled = true; return "ack"; })
.Callback(() => { Assert.True(returnsCalled); afterCalled = true; });
Assert.Equal("ack", mock.Object.Execute("ping"));
Assert.True(beforeCalled);
Assert.True(afterCalled);
}
[Fact]
public void CallbackCalledAfterReturnsCallWithArg()
{
var mock = new Mock<IFoo>();
bool returnsCalled = false;
mock.Setup(foo => foo.Execute(It.IsAny<string>()))
.Callback<string>(s => Assert.False(returnsCalled))
.Returns(() => { returnsCalled = true; return "ack"; })
.Callback<string>(s => Assert.True(returnsCalled));
mock.Object.Execute("ping");
Assert.True(returnsCalled);
}
[Fact]
public void CallbackCanReceiveABaseClass()
{
var mock = new Mock<IInterface>(MockBehavior.Strict);
mock.Setup(foo => foo.Method(It.IsAny<Derived>())).Callback<Derived>(TraceMe);
mock.Object.Method(new Derived());
}
[Fact]
public void CallbackCanBeImplementedByExtensionMethod()
{
var mock = new Mock<IFoo>();
string receivedArgument = null;
Action<string> innerCallback = param => { receivedArgument = param; };
// Delegate parameter currying can confuse Moq (used by extension delegates)
Action<string> callback = innerCallback.ExtensionCallbackHelper;
mock.Setup(x => x.Submit(It.IsAny<string>())).Callback(callback);
mock.Object.Submit("blah");
Assert.Equal("blah extended", receivedArgument);
}
[Fact]
public void CallbackWithRefParameterReceivesArguments()
{
var input = "input";
var received = default(string);
var mock = new Mock<IFoo>();
mock.Setup(f => f.Execute(ref input))
.Callback(new ExecuteRHandler((ref string arg1) =>
{
received = arg1;
}));
mock.Object.Execute(ref input);
Assert.Equal("input", input);
Assert.Equal(input, received);
}
[Fact]
public void CallbackWithRefParameterCanModifyRefParameter()
{
var value = "input";
var mock = new Mock<IFoo>();
mock.Setup(f => f.Execute(ref value))
.Callback(new ExecuteRHandler((ref string arg1) =>
{
arg1 = "output";
}));
Assert.Equal("input", value);
mock.Object.Execute(ref value);
Assert.Equal("output", value);
}
[Fact]
public void CallbackWithRefParameterCannotModifyNonRefParameter()
{
var _ = default(string);
var value = "input";
var mock = new Mock<IFoo>();
mock.Setup(f => f.Execute(ref _, value))
.Callback(new ExecuteRVHandler((ref string arg1, string arg2) =>
{
arg2 = "output";
}));
Assert.Equal("input", value);
mock.Object.Execute(ref _, value);
Assert.Equal("input", value);
}
[Fact]
public void CallbackWithIndexerSetter()
{
int x = default(int);
int result = default(int);
var mock = new Mock<IFoo>();
mock.SetupSet(f => f[10] = It.IsAny<int>())
.Callback(new Action<int, int>((x_, result_) =>
{
x = x_;
result = result_;
}));
mock.Object[10] = 5;
Assert.Equal(10, x);
Assert.Equal(5, result);
}
[Fact]
public void CallbackWithMultipleArgumentIndexerSetterWithoutAny()
{
int x = default(int);
int y = default(int);
int result = default(int);
var mock = new Mock<IFoo>();
mock.SetupSet(f => f[3, 13] = It.IsAny<int>())
.Callback(new Action<int, int, int>((x_, y_, result_) =>
{
x = x_;
y = y_;
result = result_;
}));
mock.Object[3, 13] = 2;
Assert.Equal(3, x);
Assert.Equal(13, y);
Assert.Equal(2, result);
}
public interface IInterface
{
void Method(Derived b);
}
public class Base
{
}
public class Derived : Base
{
}
private void TraceMe(Base b)
{
}
public interface IFoo
{
void Submit();
void Submit(string command);
string Submit(string arg1, string arg2);
string Submit(string arg1, string arg2, string arg3);
string Submit(string arg1, string arg2, string arg3, string arg4);
void Submit(string arg1, string arg2, string arg3, string arg4, string arg5);
void Submit(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6);
void Submit(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7);
void Submit(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8);
string Execute(string command);
string Execute(string arg1, string arg2);
string Execute(string arg1, string arg2, string arg3);
string Execute(string arg1, string arg2, string arg3, string arg4);
string Execute(string arg1, string arg2, string arg3, string arg4, string arg5);
string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6);
string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7);
string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8);
string Execute(ref string arg1);
string Execute(ref string arg1, string arg2);
int Value { get; set; }
int this[int x] { get; set; }
int this[int x, int y] { get; set; }
}
public delegate void ExecuteRHandler(ref string arg1);
public delegate void ExecuteRVHandler(ref string arg1, string arg2);
}
static class Extensions
{
public static void ExtensionCallbackHelper(this Action<string> inner, string param)
{
inner.Invoke(param + " extended");
}
}
}
| |
//
// WidgetEditSession.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Xml;
using System.Reflection;
using System.Collections;
using System.CodeDom;
using Mono.Unix;
namespace Stetic {
internal class WidgetEditSession: MarshalByRefObject, IDisposable
{
string sourceWidget;
Stetic.ProjectBackend sourceProject;
Stetic.ProjectBackend gproject;
Stetic.Wrapper.Container rootWidget;
Stetic.WidgetDesignerBackend widget;
Gtk.VBox designer;
Gtk.Plug plug;
bool autoCommitChanges;
WidgetActionBar toolbar;
WidgetDesignerFrontend frontend;
bool allowBinding;
bool disposed;
ContainerUndoRedoManager undoManager;
UndoQueue undoQueue;
public event EventHandler ModifiedChanged;
public event EventHandler RootWidgetChanged;
public event Stetic.Wrapper.WidgetEventHandler SelectionChanged;
public WidgetEditSession (ProjectBackend sourceProject, WidgetDesignerFrontend frontend, string windowName, Stetic.ProjectBackend editingBackend, bool autoCommitChanges)
{
this.frontend = frontend;
this.autoCommitChanges = autoCommitChanges;
undoManager = new ContainerUndoRedoManager ();
undoQueue = new UndoQueue ();
undoManager.UndoQueue = undoQueue;
sourceWidget = windowName;
this.sourceProject = sourceProject;
if (!autoCommitChanges) {
// Reuse the action groups and icon factory of the main project
gproject = editingBackend;
// Attach will prevent the destruction of the action group list by gproject
gproject.AttachActionGroups (sourceProject.ActionGroups);
gproject.IconFactory = sourceProject.IconFactory;
gproject.FileName = sourceProject.FileName;
gproject.ImagesRootPath = sourceProject.ImagesRootPath;
gproject.ResourceProvider = sourceProject.ResourceProvider;
gproject.WidgetLibraries = (ArrayList) sourceProject.WidgetLibraries.Clone ();
gproject.InternalWidgetLibraries = (ArrayList) sourceProject.InternalWidgetLibraries.Clone ();
gproject.TargetGtkVersion = sourceProject.TargetGtkVersion;
sourceProject.ComponentTypesChanged += OnSourceProjectLibsChanged;
sourceProject.ProjectReloaded += OnSourceProjectReloaded;
rootWidget = editingBackend.GetTopLevelWrapper (sourceWidget, false);
if (rootWidget == null) {
// Copy the widget to edit from the source project
// When saving the file, this project will be merged with the main project.
sourceProject.CopyWidgetToProject (windowName, gproject, windowName);
rootWidget = gproject.GetTopLevelWrapper (windowName, true);
}
gproject.Modified = false;
}
else {
rootWidget = sourceProject.GetTopLevelWrapper (windowName, true);
gproject = sourceProject;
}
rootWidget.Select ();
undoManager.RootObject = rootWidget;
gproject.ModifiedChanged += new EventHandler (OnModifiedChanged);
gproject.Changed += new EventHandler (OnChanged);
gproject.ProjectReloaded += new EventHandler (OnProjectReloaded);
gproject.ProjectReloading += new EventHandler (OnProjectReloading);
// gproject.WidgetMemberNameChanged += new Stetic.Wrapper.WidgetNameChangedHandler (OnWidgetNameChanged);
}
public bool AllowWidgetBinding {
get { return allowBinding; }
set {
allowBinding = value;
if (toolbar != null)
toolbar.AllowWidgetBinding = allowBinding;
}
}
public Stetic.Wrapper.Widget GladeWidget {
get { return rootWidget; }
}
public Stetic.Wrapper.Container RootWidget {
get { return (Wrapper.Container) Component.GetSafeReference (rootWidget); }
}
public Gtk.Widget WrapperWidget {
get {
if (designer == null) {
if (rootWidget == null)
return widget;
Gtk.Container wc = rootWidget.Wrapped as Gtk.Container;
if (widget == null)
widget = Stetic.UserInterface.CreateWidgetDesigner (wc, rootWidget.DesignWidth, rootWidget.DesignHeight);
toolbar = new WidgetActionBar (frontend, rootWidget);
toolbar.AllowWidgetBinding = allowBinding;
designer = new Gtk.VBox ();
designer.BorderWidth = 3;
designer.PackStart (toolbar, false, false, 0);
designer.PackStart (widget, true, true, 3);
widget.DesignArea.SetSelection (gproject.Selection, gproject.Selection, false);
widget.SelectionChanged += OnSelectionChanged;
}
return designer;
}
}
[NoGuiDispatch]
public void CreateWrapperWidgetPlug (uint socketId)
{
Gdk.Threads.Enter ();
plug = new Gtk.Plug (socketId);
plug.Add (WrapperWidget);
plug.Decorated = false;
plug.ShowAll ();
Gdk.Threads.Leave ();
}
public void DestroyWrapperWidgetPlug ()
{
if (designer != null) {
Gtk.Plug plug = (Gtk.Plug) WrapperWidget.Parent;
plug.Remove (WrapperWidget);
plug.Destroy ();
}
}
public void Save ()
{
if (!autoCommitChanges) {
gproject.CopyWidgetToProject (rootWidget.Wrapped.Name, sourceProject, sourceWidget);
sourceWidget = rootWidget.Wrapped.Name;
gproject.Modified = false;
}
}
public ProjectBackend EditingBackend {
get { return gproject; }
}
public void Dispose ()
{
sourceProject.ComponentTypesChanged -= OnSourceProjectLibsChanged;
sourceProject.ProjectReloaded -= OnSourceProjectReloaded;
gproject.ModifiedChanged -= new EventHandler (OnModifiedChanged);
gproject.Changed -= new EventHandler (OnChanged);
gproject.ProjectReloaded -= OnProjectReloaded;
gproject.ProjectReloading -= OnProjectReloading;
// gproject.WidgetMemberNameChanged -= new Stetic.Wrapper.WidgetNameChangedHandler (OnWidgetNameChanged);
if (!autoCommitChanges) {
// Don't dispose the project here! it will be disposed by the frontend
if (widget != null) {
widget.SelectionChanged -= OnSelectionChanged;
// Don't dispose the widget. It will be disposed when destroyed together
// with the container
widget = null;
}
}
if (plug != null)
plug.Destroy ();
gproject = null;
rootWidget = null;
frontend = null;
System.Runtime.Remoting.RemotingServices.Disconnect (this);
disposed = true;
}
public bool Disposed {
get { return disposed; }
}
public override object InitializeLifetimeService ()
{
// Will be disconnected when calling Dispose
return null;
}
public void SetDesignerActive ()
{
widget.UpdateObjectViewers ();
}
public bool Modified {
get { return gproject.Modified; }
}
public UndoQueue UndoQueue {
get {
if (undoQueue != null)
return undoQueue;
else
return UndoQueue.Empty;
}
}
void OnModifiedChanged (object s, EventArgs a)
{
if (frontend != null)
frontend.NotifyModifiedChanged ();
}
void OnChanged (object s, EventArgs a)
{
if (frontend != null)
frontend.NotifyChanged ();
}
void OnSourceProjectReloaded (object s, EventArgs a)
{
// Propagate gtk version change
if (sourceProject.TargetGtkVersion != gproject.TargetGtkVersion)
gproject.TargetGtkVersion = sourceProject.TargetGtkVersion;
}
void OnSourceProjectLibsChanged (object s, EventArgs a)
{
// If component types have changed in the source project, they must also change
// in this project.
gproject.WidgetLibraries = (ArrayList) sourceProject.WidgetLibraries.Clone ();
gproject.InternalWidgetLibraries = (ArrayList) sourceProject.InternalWidgetLibraries.Clone ();
gproject.NotifyComponentTypesChanged ();
}
void OnProjectReloading (object s, EventArgs a)
{
if (frontend != null)
frontend.NotifyRootWidgetChanging ();
}
void OnProjectReloaded (object s, EventArgs a)
{
// Update the actions group list
if (!autoCommitChanges) {
gproject.AttachActionGroups (sourceProject.ActionGroups);
gproject.WidgetLibraries = (ArrayList) sourceProject.WidgetLibraries.Clone ();
gproject.InternalWidgetLibraries = (ArrayList) sourceProject.InternalWidgetLibraries.Clone ();
}
Gtk.Widget[] tops = gproject.Toplevels;
if (tops.Length > 0) {
rootWidget = Stetic.Wrapper.Container.Lookup (tops[0]);
undoManager.RootObject = rootWidget;
if (rootWidget != null) {
Gtk.Widget oldWidget = designer;
if (widget != null) {
widget.SelectionChanged -= OnSelectionChanged;
widget = null;
}
OnRootWidgetChanged ();
if (oldWidget != null) {
// Delay the destruction of the old widget, so the designer has time to
// show the new widget. This avoids flickering.
GLib.Timeout.Add (500, delegate {
oldWidget.Destroy ();
return false;
});
}
gproject.NotifyComponentTypesChanged ();
return;
}
}
SetErrorMode ();
}
void SetErrorMode ()
{
Gtk.Label lab = new Gtk.Label ();
lab.Markup = "<b>" + Catalog.GetString ("The form designer could not be loaded") + "</b>";
Gtk.EventBox box = new Gtk.EventBox ();
box.Add (lab);
widget = Stetic.UserInterface.CreateWidgetDesigner (box, 100, 100);
rootWidget = null;
OnRootWidgetChanged ();
}
void OnRootWidgetChanged ()
{
if (designer != null) {
if (designer.Parent is Gtk.Plug)
((Gtk.Plug)designer.Parent).Remove (designer);
designer = null;
}
if (plug != null) {
Gdk.Threads.Enter ();
plug.Add (WrapperWidget);
plug.ShowAll ();
Gdk.Threads.Leave ();
}
if (frontend != null)
frontend.NotifyRootWidgetChanged ();
if (RootWidgetChanged != null)
RootWidgetChanged (this, EventArgs.Empty);
}
void OnSelectionChanged (object ob, EventArgs a)
{
if (frontend != null) {
bool canCut, canCopy, canPaste, canDelete;
ObjectWrapper obj = ObjectWrapper.Lookup (widget.Selection);
Stetic.Wrapper.Widget wrapper = obj as Stetic.Wrapper.Widget;
IEditableObject editable = widget.Selection as IEditableObject;
if (editable == null)
editable = obj as IEditableObject;
if (editable != null) {
canCut = editable.CanCut;
canCopy = editable.CanCopy;
canPaste = editable.CanPaste;
canDelete = editable.CanDelete;
}
else {
canCut = canCopy = canPaste = canDelete = false;
}
frontend.NotifySelectionChanged (Component.GetSafeReference (obj), canCut, canCopy, canPaste, canDelete);
if (SelectionChanged != null)
SelectionChanged (this, new Stetic.Wrapper.WidgetEventArgs (wrapper));
}
}
public object SaveState ()
{
return null;
}
public void RestoreState (object sessionData)
{
}
internal void ClipboardCopySelection ()
{
IEditableObject editable = widget.Selection as IEditableObject;
if (editable == null)
editable = ObjectWrapper.Lookup (widget.Selection) as IEditableObject;
if (editable != null)
editable.Copy ();
}
public void ClipboardCutSelection ()
{
IEditableObject editable = widget.Selection as IEditableObject;
if (editable == null)
editable = ObjectWrapper.Lookup (widget.Selection) as IEditableObject;
if (editable != null)
editable.Cut ();
}
public void ClipboardPaste ()
{
IEditableObject editable = widget.Selection as IEditableObject;
if (editable == null)
editable = ObjectWrapper.Lookup (widget.Selection) as IEditableObject;
if (editable != null)
editable.Paste ();
}
public void DeleteSelection ()
{
IEditableObject editable = widget.Selection as IEditableObject;
if (editable == null)
editable = ObjectWrapper.Lookup (widget.Selection) as IEditableObject;
if (editable != null)
editable.Delete ();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Toucan.Sample.Models;
using Toucan.Sample.Models.ManageViewModels;
using Toucan.Sample.Services;
namespace Toucan.Sample.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
// Tags And Layers Builder - Auto Generate Tags and Layers classes containing consts for all variables for code completion - 2012-08-03
// released under MIT License
// http://www.opensource.org/licenses/mit-license.php
//
//@author Devin Reimer - AlmostLogical Software
//@website http://blog.almostlogical.com
/*
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//#define DISABLE_AUTO_GENERATION
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System.Reflection;
/// <summary>
/// Constants generator kit.
/// Note that generation by default will only happen if you use the Edit -> Generate Constants Classes menu item.
/// You can turn on auto generation by opening the ConstantsGeneratorKit.cs file and uncommenting the first line
/// defining the DISABLE_AUTO_GENERATION symbol.
/// This class uses UnityEditorInternal which is an undocumented internal feature
/// </summary>
public class ConstantClassesGenerator : MonoBehaviour
{
private const string FOLDER_LOCATION = "Scripts/_AutoGenerated/";
private static ConstantNamingStyle CONSTANT_NAMING_STYLE = ConstantNamingStyle.UppercaseWithUnderscores;
private const string DIGIT_PREFIX = "k";
private static string[] IGNORE_RESOURCES_IN_SUBFOLDERS = new string[] { "ProCore", "2DToolkit", "Plugins", "HairyPlotter" };
private static bool SHOW_SUCCESS_MESSAGE = true;
private const string TAGS_FILE_NAME = "KTags.cs";
private const string LAYERS_FILE_NAME = "KLayers.cs";
private const string SCENES_FILE_NAME = "KScenes.cs";
private const string RESOURCE_PATHS_FILE_NAME = "KResources.cs";
private static string header = "// This class is auto-generated by " + typeof(ConstantClassesGenerator).Name + ". Do not modify\n";
private static string TOTAL_SCENES_CONSTANT_NAME = CONSTANT_NAMING_STYLE == ConstantNamingStyle.UppercaseWithUnderscores ? "TOTAL_SCENES" : "TotalScenes";
[MenuItem( "Edit/Generate Constants Classes..." )]
static void rebuildConstantsClassesMenuItem()
{
rebuildConstantsClasses();
}
public static void rebuildConstantsClasses( bool buildResources = true, bool buildScenes = true, bool buildTagsAndLayers = true )
{
var folderPath = Application.dataPath + "/" + FOLDER_LOCATION;
if( !Directory.Exists(folderPath ) )
Directory.CreateDirectory( folderPath );
if( buildTagsAndLayers )
{
File.WriteAllText( folderPath + TAGS_FILE_NAME, getClassContent( TAGS_FILE_NAME.Replace( ".cs", string.Empty ), UnityEditorInternal.InternalEditorUtility.tags ) );
File.WriteAllText( folderPath + LAYERS_FILE_NAME, getLayerClassContent( LAYERS_FILE_NAME.Replace( ".cs", string.Empty ), UnityEditorInternal.InternalEditorUtility.layers ) );
AssetDatabase.ImportAsset( "Assets/" + FOLDER_LOCATION + TAGS_FILE_NAME, ImportAssetOptions.ForceUpdate );
AssetDatabase.ImportAsset( "Assets/" + FOLDER_LOCATION + LAYERS_FILE_NAME, ImportAssetOptions.ForceUpdate );
}
if( buildScenes )
{
File.WriteAllText( folderPath + SCENES_FILE_NAME, getEnumContent( SCENES_FILE_NAME.Replace( ".cs", string.Empty ), editorBuildSettingsScenesToNameStrings( EditorBuildSettings.scenes ) ) );
AssetDatabase.ImportAsset( "Assets/" + FOLDER_LOCATION + SCENES_FILE_NAME, ImportAssetOptions.ForceUpdate );
}
if( buildResources )
{
File.WriteAllText( folderPath + RESOURCE_PATHS_FILE_NAME, getResourcePathsContent( RESOURCE_PATHS_FILE_NAME.Replace( ".cs", string.Empty ) ) );
AssetDatabase.ImportAsset( "Assets/" + FOLDER_LOCATION + RESOURCE_PATHS_FILE_NAME, ImportAssetOptions.ForceUpdate );
}
if( SHOW_SUCCESS_MESSAGE && buildResources && buildScenes && buildTagsAndLayers )
Debug.Log( "ConstantsGeneratorKit complete. Constants classes built to " + FOLDER_LOCATION );
}
private static string[] editorBuildSettingsScenesToNameStrings( EditorBuildSettingsScene[] scenes )
{
var sceneNames = new string[scenes.Length];
for( var n = 0; n < sceneNames.Length; n++ )
sceneNames[n] = Path.GetFileNameWithoutExtension( scenes[n].path );
return sceneNames;
}
private static string getEnumContent( string className, string[] labelsArray )
{
string output = "";
output += header;
output += "public enum " + className + "\n";
output += "{\n";
int i=0;
foreach( var label in labelsArray ) {
output += "\t" + label;
output += " = " + i;
if (i < labelsArray.Length - 1)
output += ",\n";
else
output += "\n";
++i;
}
output += "\n";
output += "}";
return output;
}
private static string getClassContent( string className, string[] labelsArray )
{
var output = "";
output += header;
output += "public static class " + className + "\n";
output += "{\n";
foreach( var label in labelsArray )
output += "\t" + buildConstVariable( label ) + "\n";
if( className == SCENES_FILE_NAME.Replace( ".cs", string.Empty ) )
{
output += "\n\tpublic const int " + TOTAL_SCENES_CONSTANT_NAME + " = " + labelsArray.Length + ";\n\n";
}
output += "}";
return output;
}
private class Resource
{
public string name;
public string path;
public Resource( string path )
{
// get the path from the Resources folder root with normalized slashes
string fullAssetsPath = Path.GetFullPath("Assets").Replace('\\', '/');
path = path.Replace('\\', '/');
path = path.Replace(fullAssetsPath, "");
var parts = path.Split( new string[] { "Resources/" }, StringSplitOptions.RemoveEmptyEntries );
// strip the extension from the path
this.path = parts[1].Replace( Path.GetFileName( parts[1] ), Path.GetFileNameWithoutExtension( parts[1] ) );
this.name = Path.GetFileNameWithoutExtension( parts[1] );
}
}
private static string getResourcePathsContent( string className )
{
var output = "";
output += header;
output += "public static class " + className + "\n";
output += "{\n";
// find all our Resources folders
var dirs = Directory.GetDirectories( Application.dataPath, "Resources", SearchOption.AllDirectories );
var resources = new List<Resource>();
foreach( var dir in dirs )
{
// limit our ignored folders
var shouldAddFolder = true;
foreach( var ignoredDir in IGNORE_RESOURCES_IN_SUBFOLDERS )
{
if( dir.Contains( ignoredDir ) )
{
shouldAddFolder = false;
continue;
}
}
if( shouldAddFolder )
resources.AddRange( getAllResourcesAtPath( dir ) );
}
var resourceNamesAdded = new List<string>();
var constantNamesAdded = new List<string>();
foreach( var res in resources )
{
if( resourceNamesAdded.Contains( res.name ) )
{
Debug.LogWarning( "multiple resources with name " + res.name + " found. Skipping " + res.path );
continue;
}
string constantName = formatConstVariableName(res.name);
if( constantNamesAdded.Contains( constantName ) )
{
Debug.LogWarning( "multiple resources with constant name " + constantName + " found. Skipping " + res.path );
continue;
}
output += "\t" + buildConstVariable( res.name, "", res.path ) + "\n";
resourceNamesAdded.Add( res.name );
constantNamesAdded.Add( constantName );
}
output += "}";
return output;
}
private static List<Resource> getAllResourcesAtPath( string path )
{
var resources = new List<Resource>();
// handle files
var files = Directory.GetFiles( path, "*", SearchOption.AllDirectories );
foreach( var f in files )
{
if( f.EndsWith( ".meta" ) || f.EndsWith( ".db" ) || f.EndsWith( ".DS_Store" ) )
continue;
resources.Add( new Resource( f ) );
}
return resources;
}
private static string getLayerClassContent( string className, string[] labelsArray )
{
var output = "";
output += header;
output += "public static class " + className + "\n";
output += "{\n";
foreach( var label in labelsArray )
output += "\t" + "public const int " + formatConstVariableName( label ) + " = " + LayerMask.NameToLayer( label ) + ";\n";
output += "\n\n";
output += @" public static int onlyIncluding( params int[] layers )
{
int mask = 0;
for( var i = 0; i < layers.Length; i++ )
mask |= ( 1 << layers[i] );
return mask;
}
public static int everythingBut( params int[] layers )
{
return ~onlyIncluding( layers );
}";
output += "\n";
output += "}";
return output;
}
private static string buildConstVariable( string varName, string suffix = "", string value = null )
{
value = value ?? varName;
return "public const string " + formatConstVariableName( varName ) + suffix + " = " + '"' + value + '"' + ";";
}
private static string formatConstVariableName( string input )
{
switch ( CONSTANT_NAMING_STYLE ) {
case ConstantNamingStyle.UppercaseWithUnderscores:
return toUpperCaseWithUnderscores( input );
case ConstantNamingStyle.CamelCase:
return toCamelCase( input );
default:
return toUpperCaseWithUnderscores( input );
}
}
private static string toCamelCase( string input )
{
input = input.Replace( " ", "" );
if ( char.IsLower(input[0]) )
input = char.ToUpper( input[0] ) + input.Substring( 1 );
// uppercase letters before dash or underline
Func<char,int,string> func = ( x, i ) =>{
if ( x == '-' || x == '_' )
return "";
if( i > 0 && (input[i - 1] == '-' || input[i - 1] == '_') )
return x.ToString().ToUpper();
return x.ToString();
};
input = string.Concat( input.Select( func ).ToArray() );
// digits are a no-no so stick prefix in front
if( char.IsDigit( input[0] ) )
return DIGIT_PREFIX + input;
return input;
}
private static string toUpperCaseWithUnderscores( string input )
{
input = input.Replace( "-", "_" );
input = Regex.Replace( input, @"\s+", "_" );
// make camel-case have an underscore between letters
Func<char,int,string> func = ( x, i ) =>
{
if( i > 0 && char.IsUpper( x ) && char.IsLower( input[i - 1] ) )
return "_" + x.ToString();
return x.ToString();
};
input = string.Concat( input.Select( func ).ToArray() );
// digits are a no-no so stick prefix in front
if( char.IsDigit( input[0] ) )
return DIGIT_PREFIX + input.ToUpper();
return input.ToUpper();
}
private enum ConstantNamingStyle {
UppercaseWithUnderscores,
CamelCase
}
}
#if !DISABLE_AUTO_GENERATION
// this post processor listens for changes to the TagManager and automatically rebuilds all classes if it sees a change
public class ConstandsGeneratorPostProcessor : AssetPostprocessor
{
// for some reason, OnPostprocessAllAssets often gets called multiple times in a row. This helps guard against rebuilding classes
// when not necessary.
static DateTime? _lastTagsAndLayersBuildTime;
static DateTime? _lastScenesBuildTime;
static void OnPostprocessAllAssets( string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths )
{
var resourcesDidChange = importedAssets.Any( s => Regex.IsMatch( s, @"/Resources/.*", System.Text.RegularExpressions.RegexOptions.IgnoreCase ) );
if( !resourcesDidChange )
resourcesDidChange = movedAssets.Any( s => Regex.IsMatch( s, @"/Resources/.*", System.Text.RegularExpressions.RegexOptions.IgnoreCase ) );
if( !resourcesDidChange )
resourcesDidChange = deletedAssets.Any( s => Regex.IsMatch( s, @"/Resources/.*", System.Text.RegularExpressions.RegexOptions.IgnoreCase ) );
if( resourcesDidChange )
ConstantClassesGenerator.rebuildConstantsClasses( true, false, false );
// layers and tags changes
if( importedAssets.Contains( "ProjectSettings/TagManager.asset" ) )
{
if( !_lastTagsAndLayersBuildTime.HasValue || _lastTagsAndLayersBuildTime.Value.AddSeconds( 5 ) < DateTime.Now )
{
_lastTagsAndLayersBuildTime = DateTime.Now;
ConstantClassesGenerator.rebuildConstantsClasses( false, false );
}
}
// scene changes
if( importedAssets.Contains( "ProjectSettings/EditorBuildSettings.asset" ) )
{
if( !_lastScenesBuildTime.HasValue || _lastScenesBuildTime.Value.AddSeconds( 5 ) < DateTime.Now )
{
_lastScenesBuildTime = DateTime.Now;
ConstantClassesGenerator.rebuildConstantsClasses( false, true );
}
}
}
}
#endif
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.PropertyEditors;
using umbraco.interfaces;
using Umbraco.Core.Exceptions;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the DataType Service, which is an easy access to operations involving <see cref="IDataTypeDefinition"/>
/// </summary>
public class DataTypeService : ScopeRepositoryService, IDataTypeService
{
public DataTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
}
#region Containers
public Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateContainer(int parentId, string name, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
using (var uow = UowProvider.GetUnitOfWork())
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
try
{
var container = new EntityContainer(Constants.ObjectTypes.DataTypeGuid)
{
Name = name,
ParentId = parentId,
CreatorId = userId
};
if (uow.Events.DispatchCancelable(SavingContainer, this, new SaveEventArgs<EntityContainer>(container, evtMsgs)))
{
uow.Commit();
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.AddOrUpdate(container);
uow.Commit();
uow.Events.Dispatch(SavedContainer, this, new SaveEventArgs<EntityContainer>(container, evtMsgs));
//TODO: Audit trail ?
return Attempt.Succeed(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.Success, evtMsgs));
}
catch (Exception ex)
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
}
public EntityContainer GetContainer(int containerId)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
return repo.Get(containerId);
}
}
public EntityContainer GetContainer(Guid containerId)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
return repo.Get(containerId);
}
}
public IEnumerable<EntityContainer> GetContainers(string name, int level)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
return repo.Get(name, level);
}
}
public IEnumerable<EntityContainer> GetContainers(IDataTypeDefinition dataTypeDefinition)
{
var ancestorIds = dataTypeDefinition.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var asInt = x.TryConvertTo<int>();
if (asInt) return asInt.Result;
return int.MinValue;
})
.Where(x => x != int.MinValue && x != dataTypeDefinition.Id)
.ToArray();
return GetContainers(ancestorIds);
}
public IEnumerable<EntityContainer> GetContainers(int[] containerIds)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
return repo.GetAll(containerIds);
}
}
public Attempt<OperationStatus> SaveContainer(EntityContainer container, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
if (container.ContainedObjectType != Constants.ObjectTypes.DataTypeGuid)
{
var ex = new InvalidOperationException("Not a " + Constants.ObjectTypes.DataTypeGuid + " container.");
return OperationStatus.Exception(evtMsgs, ex);
}
if (container.HasIdentity && container.IsPropertyDirty("ParentId"))
{
var ex = new InvalidOperationException("Cannot save a container with a modified parent, move the container instead.");
return OperationStatus.Exception(evtMsgs, ex);
}
using (var uow = UowProvider.GetUnitOfWork())
{
if (uow.Events.DispatchCancelable(SavingContainer, this, new SaveEventArgs<EntityContainer>(container, evtMsgs)))
return OperationStatus.Cancelled(evtMsgs);
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
repo.AddOrUpdate(container);
uow.Commit();
uow.Events.Dispatch(SavedContainer, this, new SaveEventArgs<EntityContainer>(container, evtMsgs));
}
//TODO: Audit trail ?
return OperationStatus.Success(evtMsgs);
}
public Attempt<OperationStatus> DeleteContainer(int containerId, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
using (var uow = UowProvider.GetUnitOfWork())
{
var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs);
if (uow.Events.DispatchCancelable(DeletingContainer, this, new DeleteEventArgs<EntityContainer>(container, evtMsgs)))
{
uow.Commit();
return Attempt.Fail(new OperationStatus(OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.Delete(container);
uow.Commit();
uow.Events.Dispatch(DeletedContainer, this, new DeleteEventArgs<EntityContainer>(container, evtMsgs));
return OperationStatus.Success(evtMsgs);
//TODO: Audit trail ?
}
}
#endregion
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its Name
/// </summary>
/// <param name="name">Name of the <see cref="IDataTypeDefinition"/></param>
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionByName(string name)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.GetByQuery(new Query<IDataTypeDefinition>().Where(x => x.Name == name)).FirstOrDefault();
}
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IDataTypeDefinition"/></param>
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionById(int id)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.Get(id);
}
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its unique guid Id
/// </summary>
/// <param name="id">Unique guid Id of the DataType</param>
/// <returns><see cref="IDataTypeDefinition"/></returns>
public IDataTypeDefinition GetDataTypeDefinitionById(Guid id)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
var query = Query<IDataTypeDefinition>.Builder.Where(x => x.Key == id);
var definitions = repository.GetByQuery(query);
return definitions.FirstOrDefault();
}
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its control Id
/// </summary>
/// <param name="id">Id of the DataType control</param>
/// <returns>Collection of <see cref="IDataTypeDefinition"/> objects with a matching contorl id</returns>
[Obsolete("Property editor's are defined by a string alias from version 7 onwards, use the overload GetDataTypeDefinitionByPropertyEditorAlias instead")]
public IEnumerable<IDataTypeDefinition> GetDataTypeDefinitionByControlId(Guid id)
{
var alias = LegacyPropertyEditorIdToAliasConverter.GetAliasFromLegacyId(id, true);
return GetDataTypeDefinitionByPropertyEditorAlias(alias);
}
/// <summary>
/// Gets a <see cref="IDataTypeDefinition"/> by its control Id
/// </summary>
/// <param name="propertyEditorAlias">Alias of the property editor</param>
/// <returns>Collection of <see cref="IDataTypeDefinition"/> objects with a matching contorl id</returns>
public IEnumerable<IDataTypeDefinition> GetDataTypeDefinitionByPropertyEditorAlias(string propertyEditorAlias)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
var query = Query<IDataTypeDefinition>.Builder.Where(x => x.PropertyEditorAlias == propertyEditorAlias);
return repository.GetByQuery(query);
}
}
/// <summary>
/// Gets all <see cref="IDataTypeDefinition"/> objects or those with the ids passed in
/// </summary>
/// <param name="ids">Optional array of Ids</param>
/// <returns>An enumerable list of <see cref="IDataTypeDefinition"/> objects</returns>
public IEnumerable<IDataTypeDefinition> GetAllDataTypeDefinitions(params int[] ids)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets all prevalues for an <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="id">Id of the <see cref="IDataTypeDefinition"/> to retrieve prevalues from</param>
/// <returns>An enumerable list of string values</returns>
public IEnumerable<string> GetPreValuesByDataTypeId(int id)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
//now convert the collection to a string list
var collection = repository.GetPreValuesCollectionByDataTypeId(id);
//now convert the collection to a string list
return collection.FormatAsDictionary().Select(x => x.Value.Value).ToList();
}
}
/// <summary>
/// Returns the PreValueCollection for the specified data type
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public PreValueCollection GetPreValuesCollectionByDataTypeId(int id)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.GetPreValuesCollectionByDataTypeId(id);
}
}
/// <summary>
/// Gets a specific PreValue by its Id
/// </summary>
/// <param name="id">Id of the PreValue to retrieve the value from</param>
/// <returns>PreValue as a string</returns>
public string GetPreValueAsString(int id)
{
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
return repository.GetPreValueAsString(id);
}
}
public Attempt<OperationStatus<MoveOperationStatusType>> Move(IDataTypeDefinition toMove, int parentId)
{
var evtMsgs = EventMessagesFactory.Get();
var moveInfo = new List<MoveEventInfo<IDataTypeDefinition>>();
using (var uow = UowProvider.GetUnitOfWork())
{
var moveEventInfo = new MoveEventInfo<IDataTypeDefinition>(toMove, toMove.Path, parentId);
var moveEventArgs = new MoveEventArgs<IDataTypeDefinition>(evtMsgs, moveEventInfo);
if (uow.Events.DispatchCancelable(Moving, this, moveEventArgs))
{
uow.Commit();
return Attempt.Fail(new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DataTypeContainerGuid);
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
try
{
EntityContainer container = null;
if (parentId > 0)
{
container = containerRepository.Get(parentId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
moveInfo.AddRange(repository.Move(toMove, container));
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
}
uow.Commit();
moveEventArgs.MoveInfoCollection = moveInfo;
moveEventArgs.CanCancel = false;
uow.Events.Dispatch(Moved, this, moveEventArgs);
}
return Attempt.Succeed(
new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.Success, evtMsgs));
}
/// <summary>
/// Saves an <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to save</param>
/// <param name="userId">Id of the user issueing the save</param>
public void Save(IDataTypeDefinition dataTypeDefinition, int userId = 0)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var saveEventArgs = new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition);
if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs))
{
uow.Commit();
return;
}
if (string.IsNullOrWhiteSpace(dataTypeDefinition.Name))
{
throw new ArgumentException("Cannot save datatype with empty name.");
}
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
dataTypeDefinition.CreatorId = userId;
repository.AddOrUpdate(dataTypeDefinition);
saveEventArgs.CanCancel = false;
uow.Events.Dispatch(Saved, this, saveEventArgs);
Audit(uow, AuditType.Save, "Save DataTypeDefinition performed by user", userId, dataTypeDefinition.Id);
uow.Commit();
}
}
/// <summary>
/// Saves a collection of <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="dataTypeDefinitions"><see cref="IDataTypeDefinition"/> to save</param>
/// <param name="userId">Id of the user issueing the save</param>
public void Save(IEnumerable<IDataTypeDefinition> dataTypeDefinitions, int userId = 0)
{
Save(dataTypeDefinitions, userId, true);
}
/// <summary>
/// Saves a collection of <see cref="IDataTypeDefinition"/>
/// </summary>
/// <param name="dataTypeDefinitions"><see cref="IDataTypeDefinition"/> to save</param>
/// <param name="userId">Id of the user issueing the save</param>
/// <param name="raiseEvents">Boolean indicating whether or not to raise events</param>
public void Save(IEnumerable<IDataTypeDefinition> dataTypeDefinitions, int userId, bool raiseEvents)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var saveEventArgs = new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinitions);
if (raiseEvents)
{
if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs))
{
uow.Commit();
return;
}
}
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
foreach (var dataTypeDefinition in dataTypeDefinitions)
{
dataTypeDefinition.CreatorId = userId;
repository.AddOrUpdate(dataTypeDefinition);
}
if (raiseEvents)
{
saveEventArgs.CanCancel = false;
uow.Events.Dispatch(Saved, this, saveEventArgs);
}
Audit(uow, AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, -1);
uow.Commit();
}
}
/// <summary>
/// Saves a list of PreValues for a given DataTypeDefinition
/// </summary>
/// <param name="dataTypeId">Id of the DataTypeDefinition to save PreValues for</param>
/// <param name="values">List of string values to save</param>
[Obsolete("This should no longer be used, use the alternative SavePreValues or SaveDataTypeAndPreValues methods instead. This will only insert pre-values without keys")]
public void SavePreValues(int dataTypeId, IEnumerable<string> values)
{
//TODO: Should we raise an event here since we are really saving values for the data type?
using (var uow = UowProvider.GetUnitOfWork())
{
var sortOrderObj =
uow.Database.ExecuteScalar<object>(
"SELECT max(sortorder) FROM cmsDataTypePreValues WHERE datatypeNodeId = @DataTypeId", new { DataTypeId = dataTypeId });
int sortOrder;
if (sortOrderObj == null || int.TryParse(sortOrderObj.ToString(), out sortOrder) == false)
{
sortOrder = 1;
}
foreach (var value in values)
{
var dto = new DataTypePreValueDto { DataTypeNodeId = dataTypeId, Value = value, SortOrder = sortOrder };
uow.Database.Insert(dto);
sortOrder++;
}
uow.Commit();
}
}
/// <summary>
/// Saves/updates the pre-values
/// </summary>
/// <param name="dataTypeId"></param>
/// <param name="values"></param>
/// <remarks>
/// We need to actually look up each pre-value and maintain it's id if possible - this is because of silly property editors
/// like 'dropdown list publishing keys'
/// </remarks>
public void SavePreValues(int dataTypeId, IDictionary<string, PreValue> values)
{
var dtd = GetDataTypeDefinitionById(dataTypeId);
if (dtd == null)
{
throw new InvalidOperationException("No data type found for id " + dataTypeId);
}
SavePreValues(dtd, values);
}
/// <summary>
/// Saves/updates the pre-values
/// </summary>
/// <param name="dataTypeDefinition"></param>
/// <param name="values"></param>
/// <remarks>
/// We need to actually look up each pre-value and maintain it's id if possible - this is because of silly property editors
/// like 'dropdown list publishing keys'
/// </remarks>
public void SavePreValues(IDataTypeDefinition dataTypeDefinition, IDictionary<string, PreValue> values)
{
//TODO: Should we raise an event here since we are really saving values for the data type?
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
repository.AddOrUpdatePreValues(dataTypeDefinition, values);
uow.Commit();
}
}
/// <summary>
/// This will save a data type and it's pre-values in one transaction
/// </summary>
/// <param name="dataTypeDefinition"></param>
/// <param name="values"></param>
/// <param name="userId"></param>
public void SaveDataTypeAndPreValues(IDataTypeDefinition dataTypeDefinition, IDictionary<string, PreValue> values, int userId = 0)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var saveEventArgs = new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition);
if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs))
{
uow.Commit();
return;
}
// if preValues contain the data type, override the data type definition accordingly
if (values != null && values.ContainsKey(Constants.PropertyEditors.PreValueKeys.DataValueType))
dataTypeDefinition.DatabaseType = PropertyValueEditor.GetDatabaseType(values[Constants.PropertyEditors.PreValueKeys.DataValueType].Value);
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
dataTypeDefinition.CreatorId = userId;
//add/update the dtd
repository.AddOrUpdate(dataTypeDefinition);
//add/update the prevalues
repository.AddOrUpdatePreValues(dataTypeDefinition, values);
Audit(uow, AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id);
uow.Commit();
saveEventArgs.CanCancel = false;
uow.Events.Dispatch(Saved, this, saveEventArgs);
}
}
/// <summary>
/// Deletes an <see cref="IDataTypeDefinition"/>
/// </summary>
/// <remarks>
/// Please note that deleting a <see cref="IDataTypeDefinition"/> will remove
/// all the <see cref="PropertyType"/> data that references this <see cref="IDataTypeDefinition"/>.
/// </remarks>
/// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to delete</param>
/// <param name="userId">Optional Id of the user issueing the deletion</param>
public void Delete(IDataTypeDefinition dataTypeDefinition, int userId = 0)
{
using (var uow = UowProvider.GetUnitOfWork())
{
var deleteEventArgs = new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition);
if (uow.Events.DispatchCancelable(Deleting, this, deleteEventArgs))
{
uow.Commit();
return;
}
var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow);
repository.Delete(dataTypeDefinition);
Audit(uow, AuditType.Delete, "Delete DataTypeDefinition performed by user", userId, dataTypeDefinition.Id);
uow.Commit();
deleteEventArgs.CanCancel = false;
uow.Events.Dispatch(Deleted, this, deleteEventArgs);
}
}
/// <summary>
/// Gets the <see cref="IDataType"/> specified by it's unique ID
/// </summary>
/// <param name="id">Id of the DataType, which corresponds to the Guid Id of the control</param>
/// <returns><see cref="IDataType"/> object</returns>
[Obsolete("IDataType is obsolete and is no longer used, it will be removed from the codebase in future versions")]
public IDataType GetDataTypeById(Guid id)
{
return DataTypesResolver.Current.GetById(id);
}
/// <summary>
/// Gets a complete list of all registered <see cref="IDataType"/>'s
/// </summary>
/// <returns>An enumerable list of <see cref="IDataType"/> objects</returns>
[Obsolete("IDataType is obsolete and is no longer used, it will be removed from the codebase in future versions")]
public IEnumerable<IDataType> GetAllDataTypes()
{
return DataTypesResolver.Current.DataTypes;
}
private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId)
{
var auditRepo = RepositoryFactory.CreateAuditRepository(uow);
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
}
#region Event Handlers
public static event TypedEventHandler<IDataTypeService, SaveEventArgs<EntityContainer>> SavingContainer;
public static event TypedEventHandler<IDataTypeService, SaveEventArgs<EntityContainer>> SavedContainer;
public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<EntityContainer>> DeletingContainer;
public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<EntityContainer>> DeletedContainer;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>> Deleting;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>> Deleted;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IDataTypeService, SaveEventArgs<IDataTypeDefinition>> Saving;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IDataTypeService, SaveEventArgs<IDataTypeDefinition>> Saved;
/// <summary>
/// Occurs before Move
/// </summary>
public static event TypedEventHandler<IDataTypeService, MoveEventArgs<IDataTypeDefinition>> Moving;
/// <summary>
/// Occurs after Move
/// </summary>
public static event TypedEventHandler<IDataTypeService, MoveEventArgs<IDataTypeDefinition>> Moved;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableListBuilderTest : ImmutableListTestBase
{
[Fact]
public void CreateBuilder()
{
ImmutableList<string>.Builder builder = ImmutableList.CreateBuilder<string>();
Assert.NotNull(builder);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableList<int>.Empty.ToBuilder();
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list = builder.ToImmutable();
Assert.Equal(builder.Count, list.Count);
builder.Add(8);
Assert.Equal(4, builder.Count);
Assert.Equal(3, list.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
}
[Fact]
public void BuilderFromList()
{
var list = ImmutableList<int>.Empty.Add(1);
var builder = list.ToBuilder();
Assert.True(builder.Contains(1));
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(4, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list2 = builder.ToImmutable();
Assert.Equal(builder.Count, list2.Count);
Assert.True(list2.Contains(1));
builder.Add(8);
Assert.Equal(5, builder.Count);
Assert.Equal(4, list2.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
Assert.False(list2.Contains(8));
}
[Fact]
public void SeveralChanges()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
var immutable1 = mutable.ToImmutable();
Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
mutable.Add(1);
var immutable2 = mutable.ToImmutable();
Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property.");
Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
Assert.Equal(1, immutable2.Count);
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10)).ToBuilder();
Assert.Equal(Enumerable.Range(1, 10), builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
Assert.Equal(Enumerable.Range(1, 11), builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(Enumerable.Range(1, 11), builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableList<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void Insert()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.Insert(0, 1);
mutable.Insert(0, 0);
mutable.Insert(2, 3);
Assert.Equal(new[] { 0, 1, 3 }, mutable);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(-1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(4, 0));
}
[Fact]
public void InsertRange()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.InsertRange(0, new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.InsertRange(1, new[] { 2, 3 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, mutable);
mutable.InsertRange(5, new[] { 6 });
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
mutable.InsertRange(5, new int[0]);
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(-1, new int[0]));
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(mutable.Count + 1, new int[0]));
}
[Fact]
public void AddRange()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.AddRange(new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.AddRange(new[] { 2, 3 });
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
mutable.AddRange(new int[0]);
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
AssertExtensions.Throws<ArgumentNullException>("items", () => mutable.AddRange(null));
}
[Fact]
public void Remove()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
Assert.False(mutable.Remove(5));
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
Assert.True(mutable.Remove(2));
Assert.Equal(new[] { 1, 3 }, mutable);
Assert.True(mutable.Remove(1));
Assert.Equal(new[] { 3 }, mutable);
Assert.True(mutable.Remove(3));
Assert.Equal(new int[0], mutable);
Assert.False(mutable.Remove(5));
}
[Fact]
public void RemoveAllBugTest()
{
var builder = ImmutableList.CreateBuilder<int>();
var elemsToRemove = new[]{0, 1, 2, 3, 4, 5}.ToImmutableHashSet();
// NOTE: this uses Add instead of AddRange because AddRange doesn't exhibit the same issue due to a different order of tree building. Don't change it without testing with the bug repro from issue #20609
foreach(var elem in new[]{0, 1, 2, 3, 4, 5, 6})
builder.Add(elem);
builder.RemoveAll(elemsToRemove.Contains);
Assert.Equal(new[]{ 6 }, builder);
}
[Fact]
public void RemoveAt()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
mutable.RemoveAt(2);
Assert.Equal(new[] { 1, 2 }, mutable);
mutable.RemoveAt(0);
Assert.Equal(new[] { 2 }, mutable);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1));
mutable.RemoveAt(0);
Assert.Equal(new int[0], mutable);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1));
}
[Fact]
public void Reverse()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Reverse();
Assert.Equal(Enumerable.Range(1, 3).Reverse(), mutable);
}
[Fact]
public void Clear()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Clear();
Assert.Equal(0, mutable.Count);
// Do it again for good measure. :)
mutable.Clear();
Assert.Equal(0, mutable.Count);
}
[Fact]
public void IsReadOnly()
{
ICollection<int> builder = ImmutableList.Create<int>().ToBuilder();
Assert.False(builder.IsReadOnly);
}
[Fact]
public void Indexer()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Equal(2, mutable[1]);
mutable[1] = 5;
Assert.Equal(5, mutable[1]);
mutable[0] = -2;
mutable[2] = -3;
Assert.Equal(new[] { -2, 5, -3 }, mutable);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[3] = 4);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1] = 4);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[3]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableList.CreateRange(seq).ToBuilder(),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableList.CreateRange(seq).ToBuilder(),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void GetEnumeratorExplicit()
{
ICollection<int> builder = ImmutableList.Create<int>().ToBuilder();
var enumerator = builder.GetEnumerator();
Assert.NotNull(enumerator);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableList.Create<int>().ToBuilder();
Assert.False(collection.IsSynchronized);
}
[Fact]
public void IListMembers()
{
IList list = ImmutableList.Create<int>().ToBuilder();
Assert.False(list.IsReadOnly);
Assert.False(list.IsFixedSize);
Assert.Equal(0, list.Add(5));
Assert.Equal(1, list.Add(8));
Assert.True(list.Contains(5));
Assert.False(list.Contains(7));
list.Insert(1, 6);
Assert.Equal(6, list[1]);
list.Remove(5);
list[0] = 9;
Assert.Equal(new[] { 9, 8 }, list.Cast<int>().ToArray());
list.Clear();
Assert.Equal(0, list.Count);
}
[Fact]
public void IList_Remove_NullArgument()
{
this.AssertIListBaseline(RemoveFunc, 1, null);
this.AssertIListBaseline(RemoveFunc, "item", null);
this.AssertIListBaseline(RemoveFunc, new int?(1), null);
this.AssertIListBaseline(RemoveFunc, new int?(), null);
}
[Fact]
public void IList_Remove_ArgTypeMismatch()
{
this.AssertIListBaseline(RemoveFunc, "first item", new object());
this.AssertIListBaseline(RemoveFunc, 1, 1.0);
this.AssertIListBaseline(RemoveFunc, new int?(1), 1);
this.AssertIListBaseline(RemoveFunc, new int?(1), new int?(1));
this.AssertIListBaseline(RemoveFunc, new int?(1), string.Empty);
}
[Fact]
public void IList_Remove_EqualsOverride()
{
this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), "foo");
this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), 3);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableList.CreateBuilder<int>());
ImmutableList<string>.Builder builder = ImmutableList.CreateBuilder<string>();
builder.Add("One");
builder.Add("Two");
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(builder);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
string[] items = itemProperty.GetValue(info.Instance) as string[];
Assert.Equal(builder, items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableList.CreateBuilder<string>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void ItemRef()
{
var list = new[] { 1, 2, 3 }.ToImmutableList();
var builder = new ImmutableList<int>.Builder(list);
ref readonly var safeRef = ref builder.ItemRef(1);
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(2, builder.ItemRef(1));
unsafeRef = 4;
Assert.Equal(4, builder.ItemRef(1));
}
[Fact]
public void ItemRef_OutOfBounds()
{
var list = new[] { 1, 2, 3 }.ToImmutableList();
var builder = new ImmutableList<int>.Builder(list);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.ItemRef(5));
}
[Fact]
public void ToImmutableList()
{
ImmutableList<int>.Builder builder = ImmutableList.CreateBuilder<int>();
builder.Add(0);
builder.Add(1);
builder.Add(2);
var list = builder.ToImmutableList();
Assert.Equal(0, builder[0]);
Assert.Equal(1, builder[1]);
Assert.Equal(2, builder[2]);
builder[1] = 5;
Assert.Equal(5, builder[1]);
Assert.Equal(1, list[1]);
builder.Clear();
Assert.True(builder.ToImmutableList().IsEmpty);
Assert.False(list.IsEmpty);
ImmutableList<int>.Builder nullBuilder = null;
AssertExtensions.Throws<ArgumentNullException>("builder", () => nullBuilder.ToImmutableList());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableList<T>.Empty.AddRange(contents).ToBuilder();
}
protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test)
{
var builder = list.ToBuilder();
var bcl = list.ToList();
int expected = bcl.RemoveAll(test);
var actual = builder.RemoveAll(test);
Assert.Equal(expected, actual);
Assert.Equal<T>(bcl, builder.ToList());
}
protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var builder = list.ToBuilder();
builder.Reverse(index, count);
Assert.Equal<T>(expected, builder.ToList());
}
internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list)
{
return list.ToBuilder();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list)
{
var builder = list.ToBuilder();
builder.Sort();
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison)
{
var builder = list.ToBuilder();
builder.Sort(comparison);
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer)
{
var builder = list.ToBuilder();
builder.Sort(comparer);
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer)
{
var builder = list.ToBuilder();
builder.Sort(index, count, comparer);
return builder.ToImmutable().ToList();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection;
using System.Xml.Serialization;
using System.Reflection.Emit;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.ComponentModel;
namespace QuickGraph.Serialization
{
public static class XmlWriterExtensions
{
public static void WriteBooleanArray(XmlWriter xmlWriter, IList<Boolean> value)
{
WriteArray<Boolean>(xmlWriter, value);
}
public static void WriteInt32Array(XmlWriter xmlWriter, IList<Int32> value)
{
WriteArray<Int32>(xmlWriter, value);
}
public static void WriteInt64Array(XmlWriter xmlWriter, IList<Int64> value)
{
WriteArray<Int64>(xmlWriter, value);
}
public static void WriteSingleArray(XmlWriter xmlWriter, IList<Single> value)
{
WriteArray<Single>(xmlWriter, value);
}
public static void WriteDoubleArray(XmlWriter xmlWriter, IList<Double> value)
{
WriteArray<Double>(xmlWriter, value);
}
public static void WriteStringArray(XmlWriter xmlWriter, IList<String> value)
{
WriteArray<String>(xmlWriter, value);
}
/// <summary>
/// Writes an array as space separated values. There is a space after every value, even the last one.
/// If array is null, it writes "null". If array is empty, it writes empty string. If array is a string array
/// with only one element "null", then it writes "null ".
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xmlWriter"></param>
/// <param name="value"></param>
public static void WriteArray<T>(XmlWriter xmlWriter, IList<T> value)
{
if (value == null)
{
xmlWriter.WriteString("null");
return;
}
var strArray = new string[value.Count];
for (int i = 0; i < value.Count; i++)
{
strArray[i] = value[i].ToString();
}
var str = String.Join(" ", strArray);
str += " ";
xmlWriter.WriteString(str);
}
}
/// <summary>
/// A GraphML ( http://graphml.graphdrawing.org/ ) format serializer.
/// </summary>
/// <typeparam name="TVertex">type of a vertex</typeparam>
/// <typeparam name="TEdge">type of an edge</typeparam>
/// <typeparam name="TGraph">type of the graph</typeparam>
/// <remarks>
/// <para>
/// Custom vertex, edge and graph attributes can be specified by
/// using the <see cref="System.Xml.Serialization.XmlAttributeAttribute"/>
/// attribute on properties (field not suppored).
/// </para>
/// <para>
/// The serializer uses LCG (lightweight code generation) to generate the
/// methods that writes the attributes to avoid paying the price of
/// Reflection on each vertex/edge. Since nothing is for free, the first
/// time you will use the serializer *on a particular pair of types*, it
/// will have to bake that method.
/// </para>
/// <para>
/// Hyperedge, nodes, nested graphs not supported.
/// </para>
/// </remarks>
public sealed class GraphMLSerializer<TVertex,TEdge,TGraph>
: SerializerBase<TVertex,TEdge>
where TEdge : IEdge<TVertex>
where TGraph : IEdgeListGraph<TVertex, TEdge>
{
#region Compiler
delegate void WriteVertexAttributesDelegate(
XmlWriter writer,
TVertex v);
delegate void WriteEdgeAttributesDelegate(
XmlWriter writer,
TEdge e);
delegate void WriteGraphAttributesDelegate(
XmlWriter writer,
TGraph e);
public static bool MoveNextData(XmlReader reader)
{
Contract.Requires(reader != null);
return
reader.NodeType == XmlNodeType.Element &&
reader.Name == "data" &&
reader.NamespaceURI == GraphMLXmlResolver.GraphMLNamespace;
}
static class WriteDelegateCompiler
{
public static readonly WriteVertexAttributesDelegate VertexAttributesWriter;
public static readonly WriteEdgeAttributesDelegate EdgeAttributesWriter;
public static readonly WriteGraphAttributesDelegate GraphAttributesWriter;
static WriteDelegateCompiler()
{
VertexAttributesWriter =
(WriteVertexAttributesDelegate)CreateWriteDelegate(
typeof(TVertex),
typeof(WriteVertexAttributesDelegate));
EdgeAttributesWriter =
(WriteEdgeAttributesDelegate)CreateWriteDelegate(
typeof(TEdge),
typeof(WriteEdgeAttributesDelegate)
);
GraphAttributesWriter =
(WriteGraphAttributesDelegate)CreateWriteDelegate(
typeof(TGraph),
typeof(WriteGraphAttributesDelegate)
);
}
static class Metadata
{
public static readonly MethodInfo WriteStartElementMethod =
typeof(XmlWriter).GetMethod(
"WriteStartElement",
BindingFlags.Instance | BindingFlags.Public);
// bcz: ,null, new Type[] { typeof(string), typeof(string) }, null);
public static readonly MethodInfo WriteEndElementMethod =
typeof(XmlWriter).GetMethod(
"WriteEndElement",
BindingFlags.Instance | BindingFlags.Public);
// bcz: , null, new Type[] { }, null);
public static readonly MethodInfo WriteStringMethod =
typeof(XmlWriter).GetMethod(
"WriteString",
BindingFlags.Instance | BindingFlags.Public);
// bcz: , null, new Type[] { typeof(string) }, null);
public static readonly MethodInfo WriteAttributeStringMethod =
typeof(XmlWriter).GetMethod(
"WriteAttributeString",
BindingFlags.Instance | BindingFlags.Public);
// bcz: ,null, new Type[] { typeof(string), typeof(string) }, null);
public static readonly MethodInfo WriteStartAttributeMethod =
typeof(XmlWriter).GetMethod(
"WriteStartAttribute",
BindingFlags.Instance | BindingFlags.Public);
// bcz: ,null, new Type[] { typeof(string) }, null);
public static readonly MethodInfo WriteEndAttributeMethod =
typeof(XmlWriter).GetMethod(
"WriteEndAttribute",
BindingFlags.Instance | BindingFlags.Public);
// bcz: , null, new Type[] { }, null);
private static readonly Dictionary<Type, MethodInfo> WriteValueMethods = new Dictionary<Type, MethodInfo>();
static Metadata()
{
var writer = typeof(XmlWriter);
WriteValueMethods.Add(typeof(bool), writer.GetMethod("WriteValue", new Type[] { typeof(bool) }));
WriteValueMethods.Add(typeof(int), writer.GetMethod("WriteValue", new Type[] { typeof(int) }));
WriteValueMethods.Add(typeof(long), writer.GetMethod("WriteValue", new Type[] { typeof(long) }));
WriteValueMethods.Add(typeof(float), writer.GetMethod("WriteValue", new Type[] { typeof(float) }));
WriteValueMethods.Add(typeof(double), writer.GetMethod("WriteValue", new Type[] { typeof(double) }));
WriteValueMethods.Add(typeof(string), writer.GetMethod("WriteString", new Type[] { typeof(string) }));
var writerExtensions = typeof(XmlWriterExtensions);
WriteValueMethods.Add(typeof(Boolean[]), writerExtensions.GetMethod("WriteBooleanArray"));
WriteValueMethods.Add(typeof(Int32[]), writerExtensions.GetMethod("WriteInt32Array"));
WriteValueMethods.Add(typeof(Int64[]), writerExtensions.GetMethod("WriteInt64Array"));
WriteValueMethods.Add(typeof(Single[]), writerExtensions.GetMethod("WriteSingleArray"));
WriteValueMethods.Add(typeof(Double[]), writerExtensions.GetMethod("WriteDoubleArray"));
WriteValueMethods.Add(typeof(String[]), writerExtensions.GetMethod("WriteStringArray"));
WriteValueMethods.Add(typeof(IList<Boolean>), writerExtensions.GetMethod("WriteBooleanArray"));
WriteValueMethods.Add(typeof(IList<Int32>), writerExtensions.GetMethod("WriteInt32Array"));
WriteValueMethods.Add(typeof(IList<Int64>), writerExtensions.GetMethod("WriteInt64Array"));
WriteValueMethods.Add(typeof(IList<Single>), writerExtensions.GetMethod("WriteSingleArray"));
WriteValueMethods.Add(typeof(IList<Double>), writerExtensions.GetMethod("WriteDoubleArray"));
WriteValueMethods.Add(typeof(IList<String>), writerExtensions.GetMethod("WriteStringArray"));
}
public static bool TryGetWriteValueMethod(Type valueType, out MethodInfo method)
{
Contract.Requires(valueType != null);
var status = WriteValueMethods.TryGetValue(valueType, out method);
return status;
}
}
public static Delegate CreateWriteDelegate(Type nodeType, Type delegateType)
{
throw new NotImplementedException();
//Contract.Requires(nodeType != null);
//Contract.Requires(delegateType != null);
//var method = new DynamicMethod(
// "Write" + delegateType.Name + nodeType.Name,
// typeof(void),
// new Type[] { typeof(XmlWriter), nodeType },
// nodeType.Module
// );
//var gen = method.GetILGenerator();
//Label @default = default(Label);
//foreach (var kv in SerializationHelper.GetAttributeProperties(nodeType))
//{
// var property = kv.Property;
// var name = kv.Name;
// var getMethod = property.GetGetMethod();
// if (getMethod == null)
// throw new NotSupportedException(String.Format("Property {0}.{1} has not getter", property.DeclaringType, property.Name));
// MethodInfo writeValueMethod;
// if (!Metadata.TryGetWriteValueMethod(property.PropertyType, out writeValueMethod))
// throw new NotSupportedException(String.Format("Property {0}.{1} type is not supported", property.DeclaringType, property.Name));
// var defaultValueAttribute =
// Attribute.GetCustomAttribute(property, typeof(DefaultValueAttribute))
// as DefaultValueAttribute;
// if (defaultValueAttribute != null)
// {
// @default = gen.DefineLabel();
// var value = defaultValueAttribute.Value;
// if (value != null &&
// value.GetType() != property.PropertyType)
// throw new InvalidOperationException("inconsistent default value of property " + property.Name);
// switch (Convert.GetTypeCode(value)) // bcz: Type.GetTypeCode(property.PropertyType))
// {
// case TypeCode.Int32:
// gen.Emit(OpCodes.Ldc_I4, (int)value);
// break;
// case TypeCode.Int64:
// gen.Emit(OpCodes.Ldc_I8, (long)value);
// break;
// case TypeCode.Single:
// gen.Emit(OpCodes.Ldc_R4, (float)value);
// break;
// case TypeCode.Double:
// gen.Emit(OpCodes.Ldc_R8, (double)value);
// break;
// case TypeCode.String:
// gen.Emit(OpCodes.Ldstr, (string)value);
// break;
// case TypeCode.Boolean:
// gen.Emit((bool)value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
// break;
// default:
// throw new InvalidOperationException("unsupported type " + property.PropertyType);
// }
// gen.Emit(OpCodes.Ldarg_1);
// gen.EmitCall(OpCodes.Callvirt, getMethod, null);
// gen.Emit(OpCodes.Ceq);
// gen.Emit(OpCodes.Brtrue, @default);
// }
// // for each property of the type,
// // write it to the xmlwriter (we need to take care of value types, etc...)
// // writer.WriteStartElement("data")
// gen.Emit(OpCodes.Ldarg_0);
// gen.Emit(OpCodes.Ldstr, "data");
// gen.Emit(OpCodes.Ldstr, GraphMLXmlResolver.GraphMLNamespace);
// gen.EmitCall(OpCodes.Callvirt, Metadata.WriteStartElementMethod, null);
// // writer.WriteStartAttribute("key");
// gen.Emit(OpCodes.Ldarg_0);
// gen.Emit(OpCodes.Ldstr, "key");
// gen.Emit(OpCodes.Ldstr, name);
// gen.EmitCall(OpCodes.Callvirt, Metadata.WriteAttributeStringMethod, null);
// // writer.WriteValue(v.xxx);
// gen.Emit(OpCodes.Ldarg_0);
// gen.Emit(OpCodes.Ldarg_1);
// gen.EmitCall(OpCodes.Callvirt, getMethod, null);
// // When reading scalar values we call member methods of XmlReader, while for array values
// // we call our own static methods. These two types of methods seem to need different opcode.
// var opcode = writeValueMethod.DeclaringType == typeof(XmlWriterExtensions) ? OpCodes.Call : OpCodes.Callvirt;
// gen.EmitCall(opcode, writeValueMethod, null);
// // writer.WriteEndElement()
// gen.Emit(OpCodes.Ldarg_0);
// gen.EmitCall(OpCodes.Callvirt, Metadata.WriteEndElementMethod, null);
// if (defaultValueAttribute != null)
// {
// gen.MarkLabel(@default);
// @default = default(Label);
// }
//}
//gen.Emit(OpCodes.Ret);
////let's bake the method
//return method.CreateDelegate(delegateType);
}
}
#endregion
public void Serialize(
XmlWriter writer,
TGraph visitedGraph,
VertexIdentity<TVertex> vertexIdentities,
EdgeIdentity<TVertex, TEdge> edgeIdentities
)
{
Contract.Requires(writer != null);
Contract.Requires(visitedGraph != null);
Contract.Requires(vertexIdentities != null);
Contract.Requires(edgeIdentities != null);
var worker = new WriterWorker(this, writer, visitedGraph, vertexIdentities, edgeIdentities);
worker.Serialize();
}
internal class WriterWorker
{
private readonly GraphMLSerializer<TVertex, TEdge,TGraph> serializer;
private readonly XmlWriter writer;
private readonly TGraph visitedGraph;
private readonly VertexIdentity<TVertex> vertexIdentities;
private readonly EdgeIdentity<TVertex, TEdge> edgeIdentities;
public WriterWorker(
GraphMLSerializer<TVertex, TEdge, TGraph> serializer,
XmlWriter writer,
TGraph visitedGraph,
VertexIdentity<TVertex> vertexIdentities,
EdgeIdentity<TVertex, TEdge> edgeIdentities)
{
Contract.Requires(serializer != null);
Contract.Requires(writer != null);
Contract.Requires(visitedGraph != null);
Contract.Requires(vertexIdentities != null);
Contract.Requires(edgeIdentities != null);
this.serializer = serializer;
this.writer = writer;
this.visitedGraph = visitedGraph;
this.vertexIdentities = vertexIdentities;
this.edgeIdentities = edgeIdentities;
}
public GraphMLSerializer<TVertex, TEdge, TGraph> Serializer
{
get { return this.serializer; }
}
public XmlWriter Writer
{
get { return this.writer; }
}
public TGraph VisitedGraph
{
get { return this.visitedGraph; }
}
public void Serialize()
{
this.WriteHeader();
this.WriteGraphAttributeDefinitions();
this.WriteVertexAttributeDefinitions();
this.WriteEdgeAttributeDefinitions();
this.WriteGraphHeader();
this.WriteVertices();
this.WriteEdges();
this.WriteGraphFooter();
this.WriteFooter();
}
private void WriteHeader()
{
if (this.Serializer.EmitDocumentDeclaration)
this.Writer.WriteStartDocument();
this.Writer.WriteStartElement("", "graphml", GraphMLXmlResolver.GraphMLNamespace);
}
private void WriteFooter()
{
this.Writer.WriteEndElement();
this.Writer.WriteEndDocument();
}
private void WriteGraphHeader()
{
this.Writer.WriteStartElement("graph", GraphMLXmlResolver.GraphMLNamespace);
this.Writer.WriteAttributeString("id", "G");
this.Writer.WriteAttributeString("edgedefault",
(this.VisitedGraph.IsDirected) ? "directed" : "undirected"
);
this.Writer.WriteAttributeString("parse.nodes", this.VisitedGraph.VertexCount.ToString());
this.Writer.WriteAttributeString("parse.edges", this.VisitedGraph.EdgeCount.ToString());
this.Writer.WriteAttributeString("parse.order", "nodesfirst");
this.Writer.WriteAttributeString("parse.nodeids", "free");
this.Writer.WriteAttributeString("parse.edgeids", "free");
GraphMLSerializer<TVertex, TEdge, TGraph>.WriteDelegateCompiler.GraphAttributesWriter(this.Writer, this.VisitedGraph);
}
private void WriteGraphFooter()
{
this.Writer.WriteEndElement();
}
private void WriteGraphAttributeDefinitions()
{
string forNode = "graph";
Type nodeType = typeof(TGraph);
this.WriteAttributeDefinitions(forNode, nodeType);
}
private void WriteVertexAttributeDefinitions()
{
string forNode = "node";
Type nodeType = typeof(TVertex);
this.WriteAttributeDefinitions(forNode, nodeType);
}
private void WriteEdgeAttributeDefinitions()
{
string forNode = "edge";
Type nodeType = typeof(TEdge);
this.WriteAttributeDefinitions(forNode, nodeType);
}
private static string ConstructTypeCodeForSimpleType(Type t)
{
//bcz :
throw new NotImplementedException();
//switch (Type.GetTypeCode(t))
//{
// case TypeCode.Boolean:
// return "boolean";
// case TypeCode.Int32:
// return "int";
// case TypeCode.Int64:
// return "long";
// case TypeCode.Single:
// return "float";
// case TypeCode.Double:
// return "double";
// case TypeCode.String:
// return "string";
// case TypeCode.Object:
// return "object";
// default:
// return "invalid";
//}
}
private string ConstructTypeCode(Type t)
{
var code = ConstructTypeCodeForSimpleType(t);
if (code == "invalid")
{
throw new NotSupportedException("Simple type not supported by the GraphML schema");
}
// Recognize arrays of certain simple types. Typestring is still "string" for all arrays,
// because GraphML schema doesn't have an array type.
if (code == "object")
{
var it = t.Name == "IList`1" ? t :
//bcz: t.GetInterface("IList`1", false);
null;
if (it != null && it.Name == "IList`1")
{
var e = it.GetGenericArguments()[0];
var c = ConstructTypeCodeForSimpleType(e);
if (c == "object" || c == "invalid")
{
throw new NotSupportedException("Array type not supported by GraphML schema");
}
code = "string";
}
}
return code;
#if false
switch (Type.GetTypeCode(t))
{
case TypeCode.Boolean:
return "boolean";
case TypeCode.Int32:
return "int";
case TypeCode.Int64:
return "long";
case TypeCode.Single:
return "float";
case TypeCode.Double:
return "double";
case TypeCode.String:
return "string";
case TypeCode.Object:
if (t.IsArray)
{
var e = t.GetElementType();
switch(Type.GetTypeCode(e))
{
case TypeCode.Boolean:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
break;
default:
throw new NotSupportedException("This array element type is not supported by GraphML schema");
}
return "string";
}
throw new NotSupportedException("Object type other than array is not supported by GraphML schema");
default:
throw new NotSupportedException("Type not supported by the GraphML schema");
}
#endif
}
private void WriteAttributeDefinitions(string forNode, Type nodeType)
{//bcz :
throw new NotImplementedException();
//Contract.Requires(forNode != null);
//Contract.Requires(nodeType != null);
//foreach (var kv in SerializationHelper.GetAttributeProperties(nodeType))
//{
// var property = kv.Property;
// var name = kv.Name;
// Type propertyType = property.PropertyType;
// {
// //<key id="d1" for="edge" attr.name="weight" attr.type="double"/>
// this.Writer.WriteStartElement("key", GraphMLXmlResolver.GraphMLNamespace);
// this.Writer.WriteAttributeString("id", name);
// this.Writer.WriteAttributeString("for", forNode);
// this.Writer.WriteAttributeString("attr.name", name);
// string typeCodeStr;
// try
// {
// typeCodeStr = ConstructTypeCode(propertyType);
// }
// catch (NotSupportedException)
// {
// throw new NotSupportedException(String.Format("Property type {0}.{1} not supported by the GraphML schema", property.DeclaringType, property.Name));
// }
// this.Writer.WriteAttributeString("attr.type", typeCodeStr);
// }
// // <default>...</default>
// object defaultValue;
// if (kv.TryGetDefaultValue(out defaultValue))
// {
// this.Writer.WriteStartElement("default");
// var defaultValueType = defaultValue.GetType();
// switch (Type.GetTypeCode(defaultValueType))
// {
// case TypeCode.Boolean:
// this.Writer.WriteString(XmlConvert.ToString((bool)defaultValue));
// break;
// case TypeCode.Int32:
// this.Writer.WriteString(XmlConvert.ToString((int)defaultValue));
// break;
// case TypeCode.Int64:
// this.Writer.WriteString(XmlConvert.ToString((long)defaultValue));
// break;
// case TypeCode.Single:
// this.Writer.WriteString(XmlConvert.ToString((float)defaultValue));
// break;
// case TypeCode.Double:
// this.Writer.WriteString(XmlConvert.ToString((double)defaultValue));
// break;
// case TypeCode.String:
// this.Writer.WriteString((string)defaultValue);
// break;
// case TypeCode.Object:
// if (defaultValueType.IsArray)
// {
// throw new NotImplementedException("Default values for array types are not implemented");
// }
// throw new NotSupportedException(String.Format("Property type {0}.{1} not supported by the GraphML schema", property.DeclaringType, property.Name));
// default:
// throw new NotSupportedException(String.Format("Property type {0}.{1} not supported by the GraphML schema", property.DeclaringType, property.Name));
// }
// this.Writer.WriteEndElement();
// }
// this.Writer.WriteEndElement();
//}
}
private void WriteVertices()
{
foreach (var v in this.VisitedGraph.Vertices)
{
this.Writer.WriteStartElement("node", GraphMLXmlResolver.GraphMLNamespace);
this.Writer.WriteAttributeString("id", this.vertexIdentities(v));
GraphMLSerializer<TVertex, TEdge,TGraph>.WriteDelegateCompiler.VertexAttributesWriter(this.Writer, v);
this.Writer.WriteEndElement();
}
}
private void WriteEdges()
{
foreach (var e in this.VisitedGraph.Edges)
{
this.Writer.WriteStartElement("edge", GraphMLXmlResolver.GraphMLNamespace);
this.Writer.WriteAttributeString("id", this.edgeIdentities(e));
this.Writer.WriteAttributeString("source", this.vertexIdentities(e.Source));
this.Writer.WriteAttributeString("target", this.vertexIdentities(e.Target));
GraphMLSerializer<TVertex, TEdge,TGraph>.WriteDelegateCompiler.EdgeAttributesWriter(this.Writer, e);
this.Writer.WriteEndElement();
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
////////////////////////////////////////////////////////////////////////////////
namespace System.Reflection
{
using System;
////using System.Diagnostics.SymbolStore;
////using System.Runtime.Remoting;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
////using System.Reflection.Emit;
using System.Collections;
using System.Threading;
////using System.Security;
////using System.Security.Permissions;
////using System.IO;
using System.Globalization;
////using System.Runtime.Versioning;
[Flags]
[Serializable]
public enum PortableExecutableKinds
{
NotAPortableExecutableImage = 0x0,
ILOnly = 0x1,
Required32Bit = 0x2,
PE32Plus = 0x4,
Unmanaged32Bit = 0x8,
}
[Serializable]
public enum ImageFileMachine
{
I386 = 0x014c,
IA64 = 0x0200,
AMD64 = 0x8664,
}
[Serializable]
public class Module /*: ISerializable, ICustomAttributeProvider*/
{
#region FCalls
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// [SuppressUnmanagedCodeSecurity]
//// private extern static RuntimeTypeHandle GetType( ModuleHandle module, String className, bool ignoreCase, bool throwOnError );
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// [SuppressUnmanagedCodeSecurity]
//// private extern static void GetScopeName( ModuleHandle module, StringHandleOnStack retString );
////
//// [ResourceExposure( ResourceScope.Machine )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// [SuppressUnmanagedCodeSecurity]
//// private extern static void GetFullyQualifiedName( ModuleHandle module, StringHandleOnStack retString );
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private extern static Type[] GetTypes( IntPtr module, ref StackCrawlMark stackMark );
////
//// internal Type[] GetTypes( ref StackCrawlMark stackMark )
//// {
//// return GetTypes( GetNativeHandle().Value, ref stackMark );
//// }
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private extern static bool IsResource( IntPtr module );
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// [SuppressUnmanagedCodeSecurity]
//// static private extern void GetSignerCertificate( ModuleHandle module, ObjectHandleOnStack retData );
#endregion
#region Static Constructor
//// static Module()
//// {
//// __Filters _fltObj;
//// _fltObj = new __Filters();
//// FilterTypeName = new TypeFilter( _fltObj.FilterTypeName );
//// FilterTypeNameIgnoreCase = new TypeFilter( _fltObj.FilterTypeNameIgnoreCase );
//// }
#endregion
#region Public Statics
//// public static readonly TypeFilter FilterTypeName;
////
//// public static readonly TypeFilter FilterTypeNameIgnoreCase;
////
//// public MethodBase ResolveMethod( int metadataToken )
//// {
//// return ResolveMethod( metadataToken, null, null );
//// }
////
//// private static RuntimeTypeHandle[] ConvertToTypeHandleArray( Type[] genericArguments )
//// {
//// if(genericArguments == null)
//// {
//// return null;
//// }
////
//// int size = genericArguments.Length;
//// RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size];
//// for(int i = 0; i < size; i++)
//// {
//// Type typeArg = genericArguments[i];
//// if(typeArg == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidGenericInstArray" ) );
//// }
////
//// typeArg = typeArg.UnderlyingSystemType;
//// if(typeArg == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidGenericInstArray" ) );
//// }
//// if(!(typeArg is RuntimeType))
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidGenericInstArray" ) );
//// }
////
//// typeHandleArgs[i] = typeArg.GetTypeHandleInternal();
//// }
//// return typeHandleArgs;
//// }
////
//// public byte[] ResolveSignature( int metadataToken )
//// {
//// MetadataToken tk = new MetadataToken( metadataToken );
////
//// if(!MetadataImport.IsValidToken( tk ))
//// {
//// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) );
//// }
////
//// if(!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ), "metadataToken" );
//// }
////
//// ConstArray signature;
//// if(tk.IsMemberRef)
//// {
//// signature = MetadataImport.GetMemberRefProps( metadataToken );
//// }
//// else
//// {
//// signature = MetadataImport.GetSignatureFromToken( metadataToken );
//// }
////
//// byte[] sig = new byte[signature.Length];
////
//// for(int i = 0; i < signature.Length; i++)
//// {
//// sig[i] = signature[i];
//// }
////
//// return sig;
//// }
////
//// public MethodBase ResolveMethod( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments )
//// {
//// MetadataToken tk = new MetadataToken( metadataToken );
////
//// if(!MetadataImport.IsValidToken( tk ))
//// {
//// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) );
//// }
////
//// RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray( genericTypeArguments );
//// RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray( genericMethodArguments );
////
//// try
//// {
//// if(!tk.IsMethodDef && !tk.IsMethodSpec)
//// {
//// if(!tk.IsMemberRef)
//// {
//// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMethod", tk, this ) ) );
//// }
////
//// unsafe
//// {
//// ConstArray sig = MetadataImport.GetMemberRefProps( tk );
////
//// if(*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
//// {
//// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMethod" ), tk, this ) );
//// }
//// }
//// }
////
//// RuntimeMethodHandle methodHandle = GetModuleHandle().ResolveMethodHandle( tk, typeArgs, methodArgs );
//// Type declaringType = methodHandle.GetDeclaringType().GetRuntimeType();
////
//// if(declaringType.IsGenericType || declaringType.IsArray)
//// {
//// MetadataToken tkDeclaringType = new MetadataToken( MetadataImport.GetParentToken( tk ) );
////
//// if(tk.IsMethodSpec)
//// {
//// tkDeclaringType = new MetadataToken( MetadataImport.GetParentToken( tkDeclaringType ) );
//// }
////
//// declaringType = ResolveType( tkDeclaringType, genericTypeArguments, genericMethodArguments );
//// }
////
//// return System.RuntimeType.GetMethodBase( declaringType.GetTypeHandleInternal(), methodHandle );
//// }
//// catch(BadImageFormatException e)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Argument_BadImageFormatExceptionResolve" ), e );
//// }
//// }
////
//// internal FieldInfo ResolveLiteralField( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments )
//// {
//// MetadataToken tk = new MetadataToken( metadataToken );
////
//// if(!MetadataImport.IsValidToken( tk ))
//// {
//// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) );
//// }
////
//// string fieldName = MetadataImport.GetName( tk ).ToString();
//// int tkDeclaringType = MetadataImport.GetParentToken( tk );
////
//// Type declaringType = ResolveType( tkDeclaringType, genericTypeArguments, genericMethodArguments );
////
//// declaringType.GetFields();
////
//// try
//// {
//// return declaringType.GetField( fieldName,
//// BindingFlags.Static | BindingFlags.Instance |
//// BindingFlags.Public | BindingFlags.NonPublic |
//// BindingFlags.DeclaredOnly );
//// }
//// catch
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveField" ), tk, this ), "metadataToken" );
//// }
//// }
////
//// public FieldInfo ResolveField( int metadataToken )
//// {
//// return ResolveField( metadataToken, null, null );
//// }
////
//// public FieldInfo ResolveField( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments )
//// {
//// MetadataToken tk = new MetadataToken( metadataToken );
////
//// if(!MetadataImport.IsValidToken( tk ))
//// {
//// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) );
//// }
////
//// RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray( genericTypeArguments );
//// RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray( genericMethodArguments );
////
//// try
//// {
//// RuntimeFieldHandle fieldHandle = new RuntimeFieldHandle();
////
//// if(!tk.IsFieldDef)
//// {
//// if(!tk.IsMemberRef)
//// {
//// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveField" ), tk, this ) );
//// }
////
//// unsafe
//// {
//// ConstArray sig = MetadataImport.GetMemberRefProps( tk );
////
//// if(*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
//// {
//// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveField" ), tk, this ) );
//// }
//// }
////
//// fieldHandle = GetModuleHandle().ResolveFieldHandle( tk, typeArgs, methodArgs );
//// }
////
//// fieldHandle = GetModuleHandle().ResolveFieldHandle( metadataToken, typeArgs, methodArgs );
//// Type declaringType = fieldHandle.GetApproxDeclaringType().GetRuntimeType();
////
//// if(declaringType.IsGenericType || declaringType.IsArray)
//// {
//// int tkDeclaringType = GetModuleHandle().GetMetadataImport().GetParentToken( metadataToken );
////
//// declaringType = ResolveType( tkDeclaringType, genericTypeArguments, genericMethodArguments );
//// }
////
//// return System.RuntimeType.GetFieldInfo( declaringType.GetTypeHandleInternal(), fieldHandle );
//// }
//// catch(MissingFieldException)
//// {
//// return ResolveLiteralField( tk, genericTypeArguments, genericMethodArguments );
//// }
//// catch(BadImageFormatException e)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Argument_BadImageFormatExceptionResolve" ), e );
//// }
//// }
////
//// public Type ResolveType( int metadataToken )
//// {
//// return ResolveType( metadataToken, null, null );
//// }
////
//// public Type ResolveType( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments )
//// {
//// MetadataToken tk = new MetadataToken( metadataToken );
////
//// if(tk.IsGlobalTypeDefToken)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveModuleType" ), tk ), "metadataToken" );
//// }
////
//// if(!MetadataImport.IsValidToken( tk ))
//// {
//// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) );
//// }
////
//// if(!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveType" ), tk, this ), "metadataToken" );
//// }
////
//// RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray( genericTypeArguments );
//// RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray( genericMethodArguments );
////
//// try
//// {
//// Type t = GetModuleHandle().ResolveTypeHandle( metadataToken, typeArgs, methodArgs ).GetRuntimeType();
////
//// if(t == null)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveType" ), tk, this ), "metadataToken" );
//// }
////
//// return t;
//// }
//// catch(BadImageFormatException e)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Argument_BadImageFormatExceptionResolve" ), e );
//// }
//// }
////
//// public MemberInfo ResolveMember( int metadataToken )
//// {
//// return ResolveMember( metadataToken, null, null );
//// }
////
//// public MemberInfo ResolveMember( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments )
//// {
//// MetadataToken tk = new MetadataToken( metadataToken );
////
//// if(tk.IsProperty)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "InvalidOperation_PropertyInfoNotAvailable" ) );
//// }
////
//// if(tk.IsEvent)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "InvalidOperation_EventInfoNotAvailable" ) );
//// }
////
//// if(tk.IsMethodSpec || tk.IsMethodDef)
//// {
//// return ResolveMethod( metadataToken, genericTypeArguments, genericMethodArguments );
//// }
////
//// if(tk.IsFieldDef)
//// {
//// return ResolveField( metadataToken, genericTypeArguments, genericMethodArguments );
//// }
////
//// if(tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
//// {
//// return ResolveType( metadataToken, genericTypeArguments, genericMethodArguments );
//// }
////
//// if(tk.IsMemberRef)
//// {
//// if(!MetadataImport.IsValidToken( tk ))
//// {
//// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) );
//// }
////
//// ConstArray sig = MetadataImport.GetMemberRefProps( tk );
////
//// unsafe
//// {
//// if(*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
//// {
//// return ResolveField( tk, genericTypeArguments, genericMethodArguments );
//// }
//// else
//// {
//// return ResolveMethod( tk, genericTypeArguments, genericMethodArguments );
//// }
//// }
//// }
////
//// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMember", tk, this ) ) );
//// }
////
//// public string ResolveString( int metadataToken )
//// {
//// MetadataToken tk = new MetadataToken( metadataToken );
////
//// if(!tk.IsString)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Argument_ResolveString" ), metadataToken, ToString() ) );
//// }
////
//// if(!MetadataImport.IsValidToken( tk ))
//// {
//// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) );
//// }
////
//// string str = MetadataImport.GetUserString( metadataToken );
////
//// if(str == null)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Argument_ResolveString" ), metadataToken, ToString() ) );
//// }
////
//// return str;
//// }
////
//// public void GetPEKind( out PortableExecutableKinds peKind, out ImageFileMachine machine )
//// {
//// GetModuleHandle().GetPEKind( out peKind, out machine );
//// }
////
//// public int MDStreamVersion
//// {
//// get
//// {
//// return GetModuleHandle().MDStreamVersion;
//// }
//// }
////
#endregion
#region Literals
//// private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
#endregion
#region Data Members
#pragma warning disable 169
//// // If you add any data members, you need to update the native declaration ReflectModuleBaseObject.
//// internal ArrayList m_TypeBuilderList;
//// internal ISymbolWriter m_iSymWriter;
//// internal ModuleBuilderData m_moduleData;
//// private RuntimeType m_runtimeType;
//// private IntPtr m_pRefClass;
//// internal IntPtr m_pData;
//// internal IntPtr m_pInternalSymWriter;
//// private IntPtr m_pGlobals;
//// private IntPtr m_pFields;
//// internal MethodToken m_EntryPoint;
#pragma warning restore 169
#endregion
#region Constructor
//// internal Module()
//// {
//// // Construct a new module. This returns the default dynamic module.
//// // 0 is defined as being a module without an entry point (ie a DLL);
//// // This must throw because this dies in ToString() when constructed here...
//// throw new NotSupportedException( Environment.GetResourceString( ResId.NotSupported_Constructor ) );
//// //m_EntryPoint=new MethodToken(0);
//// }
#endregion
#region Private Members
//// private FieldInfo InternalGetField( String name, BindingFlags bindingAttr )
//// {
//// if(RuntimeType == null)
//// {
//// return null;
//// }
////
//// return RuntimeType.GetField( name, bindingAttr );
//// }
#endregion
#region Internal Members
//// internal virtual bool IsDynamic()
//// {
//// if(this is ModuleBuilder)
//// {
//// return true;
//// }
////
//// return false;
//// }
////
//// internal RuntimeType RuntimeType
//// {
//// get
//// {
//// unsafe
//// {
//// if(m_runtimeType == null)
//// {
//// m_runtimeType = GetModuleHandle().GetModuleTypeHandle().GetRuntimeType() as RuntimeType;
//// }
////
//// return m_runtimeType;
//// }
//// }
//// }
#endregion
#region Protected Virtuals
//// protected virtual MethodInfo GetMethodImpl( String name ,
//// BindingFlags bindingAttr ,
//// Binder binder ,
//// CallingConventions callConvention,
//// Type[] types ,
//// ParameterModifier[] modifiers )
//// {
//// if(RuntimeType == null)
//// {
//// return null;
//// }
////
//// if(types == null)
//// {
//// return RuntimeType.GetMethod( name, bindingAttr );
//// }
//// else
//// {
//// return RuntimeType.GetMethod( name, bindingAttr, binder, callConvention, types, modifiers );
//// }
//// }
////
//// internal MetadataImport MetadataImport
//// {
//// get
//// {
//// unsafe
//// {
//// return ModuleHandle.GetMetadataImport();
//// }
//// }
//// }
#endregion
#region ICustomAttributeProvider Members
//// public virtual Object[] GetCustomAttributes( bool inherit )
//// {
//// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType );
//// }
////
//// public virtual Object[] GetCustomAttributes( Type attributeType, bool inherit )
//// {
//// if(attributeType == null)
//// {
//// throw new ArgumentNullException( "attributeType" );
//// }
////
//// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
////
//// if(attributeRuntimeType == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" );
//// }
////
//// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType );
//// }
////
//// public virtual bool IsDefined( Type attributeType, bool inherit )
//// {
//// if(attributeType == null)
//// {
//// throw new ArgumentNullException( "attributeType" );
//// }
////
//// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
////
//// if(attributeRuntimeType == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "caType" );
//// }
////
//// return CustomAttribute.IsDefined( this, attributeRuntimeType );
//// }
////
#endregion
#region Public Virtuals
//// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )]
//// public virtual void GetObjectData( SerializationInfo info, StreamingContext context )
//// {
//// if(info == null)
//// {
//// throw new ArgumentNullException( "info" );
//// }
////
//// UnitySerializationHolder.GetUnitySerializationInfo( info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.Assembly );
//// }
////
//// public virtual Type GetType( String className, bool ignoreCase )
//// {
//// return GetType( className, false, ignoreCase );
//// }
////
//// public virtual Type GetType( String className )
//// {
//// return GetType( className, false, false );
//// }
////
//// public virtual Type GetType( String className, bool throwOnError, bool ignoreCase )
//// {
//// return GetType( GetNativeHandle(), className, throwOnError, ignoreCase ).GetRuntimeType();
//// }
////
//// internal string GetFullyQualifiedName()
//// {
//// String fullyQualifiedName = null;
////
//// GetFullyQualifiedName( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref fullyQualifiedName ) );
////
//// return fullyQualifiedName;
//// }
////
//// public virtual String FullyQualifiedName
//// {
//// [ResourceExposure( ResourceScope.Machine )]
//// [ResourceConsumption( ResourceScope.Machine )]
//// get
//// {
//// String fullyQualifiedName = GetFullyQualifiedName();
////
//// if(fullyQualifiedName != null)
//// {
//// bool checkPermission = true;
//// try
//// {
//// Path.GetFullPathInternal( fullyQualifiedName );
//// }
//// catch(ArgumentException)
//// {
//// checkPermission = false;
//// }
//// if(checkPermission)
//// {
//// new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand();
//// }
//// }
////
//// return fullyQualifiedName;
//// }
//// }
////
//// public virtual Type[] FindTypes( TypeFilter filter, Object filterCriteria )
//// {
//// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
////
//// Type[] c = GetTypes( ref stackMark );
//// int cnt = 0;
//// for(int i = 0; i < c.Length; i++)
//// {
//// if(filter != null && !filter( c[i], filterCriteria ))
//// {
//// c[i] = null;
//// }
//// else
//// {
//// cnt++;
//// }
//// }
//// if(cnt == c.Length)
//// {
//// return c;
//// }
////
//// Type[] ret = new Type[cnt];
////
//// cnt = 0;
//// for(int i = 0; i < c.Length; i++)
//// {
//// if(c[i] != null)
//// {
//// ret[cnt++] = c[i];
//// }
//// }
//// return ret;
//// }
////
//// public virtual Type[] GetTypes()
//// {
//// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
////
//// return GetTypes( ref stackMark );
//// }
////
#endregion
#region Public Members
//// public Guid ModuleVersionId
//// {
//// get
//// {
//// unsafe
//// {
//// Guid mvid;
////
//// MetadataImport.GetScopeProps( out mvid );
////
//// return mvid;
//// }
//// }
//// }
////
//// public int MetadataToken
//// {
//// get
//// {
//// return GetModuleHandle().GetToken();
//// }
//// }
////
//// public bool IsResource()
//// {
//// return IsResource( GetNativeHandle().Value );
//// }
////
//// public FieldInfo[] GetFields()
//// {
//// if(RuntimeType == null)
//// {
//// return new FieldInfo[0];
//// }
////
//// return RuntimeType.GetFields();
//// }
////
//// public FieldInfo[] GetFields( BindingFlags bindingFlags )
//// {
//// if(RuntimeType == null)
//// {
//// return new FieldInfo[0];
//// }
////
//// return RuntimeType.GetFields( bindingFlags );
//// }
////
//// public FieldInfo GetField( String name )
//// {
//// if(name == null)
//// {
//// throw new ArgumentNullException( "name" );
//// }
////
//// return GetField( name, Module.DefaultLookup );
//// }
////
//// public FieldInfo GetField( String name, BindingFlags bindingAttr )
//// {
//// if(name == null)
//// {
//// throw new ArgumentNullException( "name" );
//// }
////
//// return InternalGetField( name, bindingAttr );
//// }
////
//// public MethodInfo[] GetMethods()
//// {
//// if(RuntimeType == null)
//// {
//// return new MethodInfo[0];
//// }
////
//// return RuntimeType.GetMethods();
//// }
////
//// public MethodInfo[] GetMethods( BindingFlags bindingFlags )
//// {
//// if(RuntimeType == null)
//// {
//// return new MethodInfo[0];
//// }
////
//// return RuntimeType.GetMethods( bindingFlags );
//// }
////
//// public MethodInfo GetMethod( String name ,
//// BindingFlags bindingAttr ,
//// Binder binder ,
//// CallingConventions callConvention,
//// Type[] types ,
//// ParameterModifier[] modifiers )
//// {
//// if(name == null)
//// {
//// throw new ArgumentNullException( "name" );
//// }
////
//// if(types == null)
//// {
//// throw new ArgumentNullException( "types" );
//// }
////
//// for(int i = 0; i < types.Length; i++)
//// {
//// if(types[i] == null)
//// {
//// throw new ArgumentNullException( "types" );
//// }
//// }
////
//// return GetMethodImpl( name, bindingAttr, binder, callConvention, types, modifiers );
////
//// }
////
//// public MethodInfo GetMethod( String name, Type[] types )
//// {
//// if(name == null)
//// {
//// throw new ArgumentNullException( "name" );
//// }
////
//// if(types == null)
//// {
//// throw new ArgumentNullException( "types" );
//// }
////
//// for(int i = 0; i < types.Length; i++)
//// {
//// if(types[i] == null)
//// {
//// throw new ArgumentNullException( "types" );
//// }
//// }
////
//// return GetMethodImpl( name, Module.DefaultLookup, null, CallingConventions.Any, types, null );
//// }
////
//// public MethodInfo GetMethod( String name )
//// {
//// if(name == null)
//// {
//// throw new ArgumentNullException( "name" );
//// }
////
//// return GetMethodImpl( name, Module.DefaultLookup, null, CallingConventions.Any, null, null );
//// }
////
//// public String ScopeName
//// {
//// get
//// {
//// string scopeName = null;
////
//// GetScopeName( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref scopeName ) );
////
//// return scopeName;
//// }
//// }
////
//// public String Name
//// {
//// [ResourceExposure( ResourceScope.None )]
//// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )]
//// get
//// {
//// String s = GetFullyQualifiedName();
////
//// int i = s.LastIndexOf( System.IO.Path.DirectorySeparatorChar );
//// if(i == -1)
//// {
//// return s;
//// }
////
//// return new String( s.ToCharArray(), i + 1, s.Length - i - 1 );
//// }
//// }
////
//// public override String ToString()
//// {
//// return ScopeName;
//// }
////
public Assembly Assembly
{
get
{
throw new NotImplementedException();
//// return ModuleHandle.GetAssemblyHandle().GetAssembly();
}
}
//// public ModuleHandle ModuleHandle
//// {
//// get
//// {
//// //TODO: Add this back when the GetPEKind is removed from ModuleHandle
//// //if (Assembly.ReflectionOnly)
//// // throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
//// return new ModuleHandle( m_pData );
//// }
//// }
////
//// internal ModuleHandle GetModuleHandle()
//// {
//// return new ModuleHandle( m_pData );
//// }
////
//// // Returns handle for interop with EE. The handle is guaranteed to be non-null.
//// internal ModuleHandle GetNativeHandle()
//// {
//// IntPtr data = m_pData;
////
//// // This should never happen under normal circumstances. m_pData is always assigned before it is handed out to the user.
//// // There are ways how to create an unitialized objects through remoting, etc. Avoid AVing in the EE by throwing a nice
//// // exception here.
//// if(data.IsNull())
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHandle" ) );
//// }
////
//// return new ModuleHandle( data );
//// }
////
//// public System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
//// {
//// byte[] data = null;
////
//// GetSignerCertificate( GetNativeHandle(), JitHelpers.GetObjectHandleOnStack( ref data ) );
////
//// return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate( data ) : null;
//// }
#endregion
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using System.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI40;
using Net.Pkcs11Interop.HighLevelAPI40.MechanismParams;
using NUnit.Framework;
namespace Net.Pkcs11Interop.Tests.HighLevelAPI40
{
/// <summary>
/// Encryption and decryption tests.
/// </summary>
[TestFixture()]
public class _19_EncryptAndDecryptTest
{
/// <summary>
/// Single-part encryption and decryption test.
/// </summary>
[Test()]
public void _01_EncryptAndDecryptSinglePartTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RW session
using (Session session = slot.OpenSession(false))
{
// Login as normal user
session.Login(CKU.CKU_USER, Settings.NormalUserPin);
// Generate symetric key
ObjectHandle generatedKey = Helpers.GenerateKey(session);
// Generate random initialization vector
byte[] iv = session.GenerateRandom(8);
// Specify encryption mechanism with initialization vector as parameter
Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");
// Encrypt data
byte[] encryptedData = session.Encrypt(mechanism, generatedKey, sourceData);
// Do something interesting with encrypted data
// Decrypt data
byte[] decryptedData = session.Decrypt(mechanism, generatedKey, encryptedData);
// Do something interesting with decrypted data
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
session.DestroyObject(generatedKey);
session.Logout();
}
}
}
/// <summary>
/// Multi-part encryption and decryption test.
/// </summary>
[Test()]
public void _02_EncryptAndDecryptMultiPartTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RW session
using (Session session = slot.OpenSession(false))
{
// Login as normal user
session.Login(CKU.CKU_USER, Settings.NormalUserPin);
// Generate symetric key
ObjectHandle generatedKey = Helpers.GenerateKey(session);
// Generate random initialization vector
byte[] iv = session.GenerateRandom(8);
// Specify encryption mechanism with initialization vector as parameter
Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");
byte[] encryptedData = null;
byte[] decryptedData = null;
// Multipart encryption can be used i.e. for encryption of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
{
// Encrypt data
// Note that in real world application we would rather use bigger read buffer i.e. 4096
session.Encrypt(mechanism, generatedKey, inputStream, outputStream, 8);
// Read whole output stream to the byte array so we can compare results more easily
encryptedData = outputStream.ToArray();
}
// Do something interesting with encrypted data
// Multipart decryption can be used i.e. for decryption of streamed data
using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
{
// Decrypt data
// Note that in real world application we would rather use bigger read buffer i.e. 4096
session.Decrypt(mechanism, generatedKey, inputStream, outputStream, 8);
// Read whole output stream to the byte array so we can compare results more easily
decryptedData = outputStream.ToArray();
}
// Do something interesting with decrypted data
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
session.DestroyObject(generatedKey);
session.Logout();
}
}
}
/// <summary>
/// Single-part encryption and decryption test with CKM_RSA_PKCS_OAEP mechanism.
/// </summary>
[Test()]
public void _03_EncryptAndDecryptSinglePartOaepTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RW session
using (Session session = slot.OpenSession(false))
{
// Login as normal user
session.Login(CKU.CKU_USER, Settings.NormalUserPin);
// Generate key pair
ObjectHandle publicKey = null;
ObjectHandle privateKey = null;
Helpers.GenerateKeyPair(session, out publicKey, out privateKey);
// Specify mechanism parameters
CkRsaPkcsOaepParams mechanismParams = new CkRsaPkcsOaepParams((uint)CKM.CKM_SHA_1, (uint)CKG.CKG_MGF1_SHA1, (uint)CKZ.CKZ_DATA_SPECIFIED, null);
// Specify encryption mechanism with parameters
Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
// Encrypt data
byte[] encryptedData = session.Encrypt(mechanism, publicKey, sourceData);
// Do something interesting with encrypted data
// Decrypt data
byte[] decryptedData = session.Decrypt(mechanism, privateKey, encryptedData);
// Do something interesting with decrypted data
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
session.DestroyObject(privateKey);
session.DestroyObject(publicKey);
session.Logout();
}
}
}
}
}
| |
//
// HttpRequest.cs
//
// Author: najmeddine nouri
//
// Copyright (c) 2013 najmeddine nouri, amine gassem
//
// 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.
//
// Except as contained in this notice, the name(s) of the above copyright holders
// shall not be used in advertising or otherwise to promote the sale, use or other
// dealings in this Software without prior written authorization.
//
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Web;
using Badr.Net.Utils;
using log4net;
using Badr.Net.Http.Response;
namespace Badr.Net.Http.Request
{
public partial class HttpRequest
{
private static readonly ILog _Logger = LogManager.GetLogger(typeof(HttpRequest));
public const string DEFAULT_HTTP_PROTOCOL = "HTTP/1.1";
public const string WR_SEPARATOR = "\r\n";
public const char LINE1_SEPARATOR = ' ';
public const char RESOURCE_QUERY_SEPARATOR = '?';
public const char PARAMS_SEPARATOR = '&';
public const char PARAM_VALUE_SEPARATOR = '=';
public const char HEADER_VALUE_SEPARATOR = ':';
private int _headersStatus = 0;
public HttpRequest()
{
Protocol = DEFAULT_HTTP_PROTOCOL;
GET = new HttpRequestParams();
POST = new HttpRequestParams();
FILES = new HttpFormFiles();
Headers = new HttpRequestHeaders();
Cookies = new HttpCookies();
}
protected internal virtual void CreateHeaders(ReceiveBufferManager rbm)
{
if (rbm.Count > 0)
{
bool isFirstLine = true;
int eolIndex = rbm.IndexOfEol();
while (eolIndex != -1 && _headersStatus != 2)
{
ParseLine(rbm.PopString(eolIndex, 2), isFirstLine);
eolIndex = rbm.IndexOfEol();
isFirstLine = false;
}
HeaderLength = rbm.StartIndex;
ValidateHeaders();
if (!IsMulitpart)
ParseUrlEncodedParams(rbm.PopString());
}
}
protected void ValidateHeaders()
{
int contentLength;
bool contentLengthFound = int.TryParse(Headers[HttpRequestHeaders.ContentLength], out contentLength);
if (!IsSafeMethod(Method) && !contentLengthFound)
throw new HttpStatusException(HttpResponseStatus._411);
ContentLength = contentLength;
string contentType = Headers[HttpRequestHeaders.ContentType, "application/x-www-form-urlencoded"];
IsMulitpart = contentType.Contains("multipart/form-data");
if (IsMulitpart)
{
MulitpartBoundary = string.Format("--{0}", contentType.Split(';')[1].Split('=')[1].TrimStart());
MulitpartBoundaryBytes = Encoding.Default.GetBytes(MulitpartBoundary);
}
ClientGzipSupport = Headers[HttpRequestHeaders.AcceptEncoding] != null && Headers[HttpRequestHeaders.AcceptEncoding].Contains("gzip");
IsAjax = Headers[HttpRequestHeaders.XRequestedWith] == "XMLHttpRequest";
IsSecure = CheckIsSecure();
if (Headers.Contains(HttpRequestHeaders.Host))
{
DomainUri = new Uri("http://" + Headers[HttpRequestHeaders.Host]);
BuildCookies(Headers[HttpRequestHeaders.Cookie]);
}
else
throw new HttpStatusException(HttpResponseStatus._400);
}
protected virtual bool CheckIsSecure()
{
return Headers[HttpRequestHeaders.XIsHttps] == "on";
}
protected bool ParseLine(string line, bool isFirstLine)
{
if (line != null)
{
if (string.IsNullOrWhiteSpace(line))
{
if (_headersStatus == 1)
{
_headersStatus = 2;
return false;
}
}
if (isFirstLine)
{
string[] line0 = line.Split(LINE1_SEPARATOR);
if (line0 != null)
{
if (line0.Length == 1)
{
Method = HttpRequestMethods.GET;
Resource = Uri.UnescapeDataString(line0[0]);
}
else if (line0.Length > 1)
{
Method = HttpRequest.GetMethod(line0[0].Trim());
Resource = line0[1];
Protocol = line0.Length > 2 ? line0[2] : DEFAULT_HTTP_PROTOCOL;
}
string[] resources = Resource.Split(new char[] { RESOURCE_QUERY_SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
if (resources.Length > 0)
{
Resource = HttpUtility.UrlDecode(resources[0].TrimStart('/'));
// GET data
if (Method == HttpRequestMethods.GET && resources.Length > 1)
ParseUrlEncodedParams(resources[1]);
}
}
}
else
{
// Headers
if (_headersStatus != 2)
{
_headersStatus = 1;
string[] header = line.Split(HEADER_VALUE_SEPARATOR);
if (header.Length > 1 && header[1] != null)
Headers[header[0].Trim().ToLower()] = line.Substring(header[0].Length + 1).Trim();
}
}
return true;
}
return false;
}
public void RefreshFiles (HttpUploadManager uploadManager)
{
if(uploadManager != null)
FILES.AddRange(uploadManager.HttpFormFiles);
}
protected internal void ParseUrlEncodedParams(string paramsLine)
{
foreach (string param in paramsLine.Split(StringSplitOptions.RemoveEmptyEntries, PARAMS_SEPARATOR))
{
string[] paramdata = param.Split(StringSplitOptions.None, PARAM_VALUE_SEPARATOR);
if (paramdata.Length == 2)
{
AddMethodParam(paramdata[0], paramdata[1], true);
}
}
}
protected virtual void BuildCookies(string httpCookies)
{
if(httpCookies != null)
Cookies.Parse(Headers[HttpRequestHeaders.Cookie]);
}
protected internal void AddMethodParam(string name, string value, bool uriEscaped)
{
if (uriEscaped)
{
name = HttpUtility.UrlDecode(name);
value = HttpUtility.UrlDecode(value);
}
if (Method == HttpRequestMethods.GET)
GET.Add(name, value);
else
POST.Add(name, value);
}
#region Properties
public HttpRequestMethods Method { get; protected internal set; }
public string Resource { get; protected internal set; }
public string Protocol { get; protected internal set; }
public HttpRequestParams GET { get; protected internal set; }
public HttpRequestParams POST { get; protected internal set; }
public HttpFormFiles FILES { get; protected internal set; }
public HttpRequestHeaders Headers { get; protected internal set; }
public Uri DomainUri { get; protected internal set; }
public HttpCookies Cookies { get; protected internal set; }
public string Body { get; protected internal set; }
public int HeaderLength { get; private set; }
public int ContentLength { get; private set; }
public int TotalLength { get { return HeaderLength + ContentLength; } }
public bool ClientGzipSupport { get; protected set; }
public bool ValidMethod { get { return Method == HttpRequestMethods.GET || Method == HttpRequestMethods.POST; } }
public bool IsAjax { get; protected set; }
public bool IsSecure { get; protected set; }
public bool IsMulitpart { get; protected set; }
public string MulitpartBoundary { get; protected set; }
public byte[] MulitpartBoundaryBytes { get; protected set; }
#endregion
}
}
| |
/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// @Generated by gentest/gentest.rb from gentest/fixtures/YGDisplayTest.html
using System;
using NUnit.Framework;
namespace Facebook.Yoga
{
[TestFixture]
public class YGDisplayTest
{
[Test]
public void Test_display_none()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 100;
root.Height = 100;
YogaNode root_child0 = new YogaNode();
root_child0.FlexGrow = 1;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.FlexGrow = 1;
root_child1.Display = YogaDisplay.None;
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
}
[Test]
public void Test_display_none_fixed_size()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 100;
root.Height = 100;
YogaNode root_child0 = new YogaNode();
root_child0.FlexGrow = 1;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.Width = 20;
root_child1.Height = 20;
root_child1.Display = YogaDisplay.None;
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
}
[Test]
public void Test_display_none_with_margin()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 100;
root.Height = 100;
YogaNode root_child0 = new YogaNode();
root_child0.MarginLeft = 10;
root_child0.MarginTop = 10;
root_child0.MarginRight = 10;
root_child0.MarginBottom = 10;
root_child0.Width = 20;
root_child0.Height = 20;
root_child0.Display = YogaDisplay.None;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.FlexGrow = 1;
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(0f, root_child0.LayoutWidth);
Assert.AreEqual(0f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(100f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(0f, root_child0.LayoutWidth);
Assert.AreEqual(0f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(100f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
}
[Test]
public void Test_display_none_with_child()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 100;
root.Height = 100;
YogaNode root_child0 = new YogaNode();
root_child0.FlexGrow = 1;
root_child0.FlexShrink = 1;
root_child0.FlexBasis = 0.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.FlexGrow = 1;
root_child1.FlexShrink = 1;
root_child1.FlexBasis = 0.Percent();
root_child1.Display = YogaDisplay.None;
root.Insert(1, root_child1);
YogaNode root_child1_child0 = new YogaNode();
root_child1_child0.FlexGrow = 1;
root_child1_child0.FlexShrink = 1;
root_child1_child0.FlexBasis = 0.Percent();
root_child1_child0.Width = 20;
root_child1_child0.MinWidth = 0;
root_child1_child0.MinHeight = 0;
root_child1.Insert(0, root_child1_child0);
YogaNode root_child2 = new YogaNode();
root_child2.FlexGrow = 1;
root_child2.FlexShrink = 1;
root_child2.FlexBasis = 0.Percent();
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child1_child0.LayoutX);
Assert.AreEqual(0f, root_child1_child0.LayoutY);
Assert.AreEqual(0f, root_child1_child0.LayoutWidth);
Assert.AreEqual(0f, root_child1_child0.LayoutHeight);
Assert.AreEqual(50f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(100f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(50f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(50f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child1_child0.LayoutX);
Assert.AreEqual(0f, root_child1_child0.LayoutY);
Assert.AreEqual(0f, root_child1_child0.LayoutWidth);
Assert.AreEqual(0f, root_child1_child0.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(50f, root_child2.LayoutWidth);
Assert.AreEqual(100f, root_child2.LayoutHeight);
}
[Test]
public void Test_display_none_with_position()
{
YogaNode root = new YogaNode();
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 100;
root.Height = 100;
YogaNode root_child0 = new YogaNode();
root_child0.FlexGrow = 1;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode();
root_child1.FlexGrow = 1;
root_child1.Top = 10;
root_child1.Display = YogaDisplay.None;
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(100f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(0f, root_child1.LayoutWidth);
Assert.AreEqual(0f, root_child1.LayoutHeight);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
internal class ProjectExternalErrorReporter : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2
{
internal static readonly ImmutableDictionary<string, string> Properties = ImmutableDictionary<string, string>.Empty.Add(WellKnownDiagnosticPropertyNames.Origin, WellKnownDiagnosticTags.Build);
internal static readonly IReadOnlyList<string> CustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Telemetry);
internal static readonly IReadOnlyList<string> CompilerDiagnosticCustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Compiler, WellKnownDiagnosticTags.Telemetry);
private readonly ProjectId _projectId;
private readonly string _errorCodePrefix;
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly ExternalErrorDiagnosticUpdateSource _diagnosticProvider;
public ProjectExternalErrorReporter(ProjectId projectId, string errorCodePrefix, IServiceProvider serviceProvider)
{
_projectId = projectId;
_errorCodePrefix = errorCodePrefix;
_diagnosticProvider = serviceProvider.GetMefService<ExternalErrorDiagnosticUpdateSource>();
_workspace = serviceProvider.GetMefService<VisualStudioWorkspaceImpl>();
Debug.Assert(_diagnosticProvider != null);
Debug.Assert(_workspace != null);
}
public int AddNewErrors(IVsEnumExternalErrors pErrors)
{
var projectErrors = new HashSet<DiagnosticData>();
var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>();
var errors = new ExternalError[1];
uint fetched;
while (pErrors.Next(1, errors, out fetched) == VSConstants.S_OK && fetched == 1)
{
var error = errors[0];
DiagnosticData diagnostic;
if (error.bstrFileName != null)
{
diagnostic = CreateDocumentDiagnosticItem(error);
if (diagnostic != null)
{
var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>());
diagnostics.Add(diagnostic);
continue;
}
projectErrors.Add(CreateProjectDiagnosticItem(error));
}
else
{
projectErrors.Add(CreateProjectDiagnosticItem(error));
}
}
_diagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap);
return VSConstants.S_OK;
}
public int ClearAllErrors()
{
_diagnosticProvider.ClearErrors(_projectId);
return VSConstants.S_OK;
}
public int GetErrors(out IVsEnumExternalErrors pErrors)
{
pErrors = null;
Debug.Fail("This is not implemented, because no one called it.");
return VSConstants.E_NOTIMPL;
}
private DiagnosticData CreateProjectDiagnosticItem(ExternalError error)
{
return GetDiagnosticData(error);
}
private DiagnosticData CreateDocumentDiagnosticItem(ExternalError error)
{
var hostProject = _workspace.GetHostProject(_projectId);
if (!hostProject.ContainsFile(error.bstrFileName))
{
return null;
}
var hostDocument = hostProject.GetCurrentDocumentFromPath(error.bstrFileName);
var line = error.iLine;
var column = error.iCol;
var containedDocument = hostDocument as ContainedDocument;
if (containedDocument != null)
{
var span = new VsTextSpan
{
iStartLine = line,
iStartIndex = column,
iEndLine = line,
iEndIndex = column,
};
var spans = new VsTextSpan[1];
Marshal.ThrowExceptionForHR(containedDocument.ContainedLanguage.BufferCoordinator.MapPrimaryToSecondarySpan(
span,
spans));
line = spans[0].iStartLine;
column = spans[0].iStartIndex;
}
return GetDiagnosticData(error, hostDocument.Id, line, column);
}
public int ReportError(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")]VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName)
{
ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, iLine, iColumn, bstrFileName);
return VSConstants.S_OK;
}
// TODO: Use PreserveSig instead of throwing these exceptions for common cases.
public void ReportError2(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")]VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName)
{
if ((iEndLine >= 0 && iEndColumn >= 0) &&
((iEndLine < iStartLine) ||
(iEndLine == iStartLine && iEndColumn < iStartColumn)))
{
throw new ArgumentException(ServicesVSResources.EndPositionMustBeGreaterThanStart);
}
// We only handle errors that have positions. For the rest, we punt back to the
// project system.
if (iStartLine < 0 || iStartColumn < 0)
{
throw new NotImplementedException();
}
var hostProject = _workspace.GetHostProject(_projectId);
if (!hostProject.ContainsFile(bstrFileName))
{
throw new NotImplementedException();
}
var hostDocument = hostProject.GetCurrentDocumentFromPath(bstrFileName);
var priority = (VSTASKPRIORITY)nPriority;
DiagnosticSeverity severity;
switch (priority)
{
case VSTASKPRIORITY.TP_HIGH:
severity = DiagnosticSeverity.Error;
break;
case VSTASKPRIORITY.TP_NORMAL:
severity = DiagnosticSeverity.Warning;
break;
case VSTASKPRIORITY.TP_LOW:
severity = DiagnosticSeverity.Info;
break;
default:
throw new ArgumentException(ServicesVSResources.NotAValidValue, "nPriority");
}
var diagnostic = GetDiagnosticData(
hostDocument.Id, bstrErrorId, bstrErrorMessage, severity,
null, iStartLine, iStartColumn, iEndLine, iEndColumn,
bstrFileName, iStartLine, iStartColumn, iEndLine, iEndColumn);
_diagnosticProvider.AddNewErrors(hostDocument.Id, diagnostic);
}
public int ClearErrors()
{
_diagnosticProvider.ClearErrors(_projectId);
return VSConstants.S_OK;
}
private string GetErrorId(ExternalError error)
{
return string.Format("{0}{1:0000}", _errorCodePrefix, error.iErrorID);
}
private static int GetWarningLevel(DiagnosticSeverity severity)
{
return severity == DiagnosticSeverity.Error ? 0 : 1;
}
private static DiagnosticSeverity GetDiagnosticSeverity(ExternalError error)
{
return error.fError != 0 ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning;
}
private DiagnosticData GetDiagnosticData(
ExternalError error, DocumentId id = null, int line = 0, int column = 0)
{
if (id != null)
{
// save error line/column (surface buffer location) as mapped line/column so that we can display
// right location on closed Venus file.
return GetDiagnosticData(
id, GetErrorId(error), error.bstrText, GetDiagnosticSeverity(error),
null, error.iLine, error.iCol, error.iLine, error.iCol, error.bstrFileName, line, column, line, column);
}
return GetDiagnosticData(
id, GetErrorId(error), error.bstrText, GetDiagnosticSeverity(error), null, 0, 0, 0, 0, null, 0, 0, 0, 0);
}
private static bool IsCompilerDiagnostic(string errorId)
{
if (!string.IsNullOrEmpty(errorId) && errorId.Length > 2)
{
var prefix = errorId.Substring(0, 2);
if (prefix.Equals("CS", StringComparison.OrdinalIgnoreCase) || prefix.Equals("BC", StringComparison.OrdinalIgnoreCase))
{
var suffix = errorId.Substring(2);
int id;
return int.TryParse(suffix, out id);
}
}
return false;
}
private static IReadOnlyList<string> GetCustomTags(string errorId)
{
return IsCompilerDiagnostic(errorId) ? CompilerDiagnosticCustomTags : CustomTags;
}
private DiagnosticData GetDiagnosticData(
DocumentId id, string errorId, string message, DiagnosticSeverity severity,
string mappedFilePath, int mappedStartLine, int mappedStartColumn, int mappedEndLine, int mappedEndColumn,
string originalFilePath, int originalStartLine, int originalStartColumn, int originalEndLine, int originalEndColumn)
{
return new DiagnosticData(
id: errorId,
category: WellKnownDiagnosticTags.Build,
message: message,
title: message,
enuMessageForBingSearch: message, // Unfortunately, there is no way to get ENU text for this since this is an external error.
severity: severity,
defaultSeverity: severity,
isEnabledByDefault: true,
warningLevel: GetWarningLevel(severity),
customTags: GetCustomTags(errorId),
properties: Properties,
workspace: _workspace,
projectId: _projectId,
location: new DiagnosticDataLocation(id,
sourceSpan: null,
originalFilePath: originalFilePath,
originalStartLine: originalStartLine,
originalStartColumn: originalStartColumn,
originalEndLine: originalEndLine,
originalEndColumn: originalEndColumn,
mappedFilePath: mappedFilePath,
mappedStartLine: mappedStartLine,
mappedStartColumn: mappedStartColumn,
mappedEndLine: mappedEndLine,
mappedEndColumn: mappedEndColumn));
}
}
}
| |
/*
* Copyright (c) Contributors, OpenCurrency Team
* 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 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.
*
* Major changes.
* Michael E. Steurer, 2011
* Institute for Information Systems and Computer Media
* Graz University of Technology
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.Xml;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using LitJson;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OMEconomy.OMBase;
[assembly: Addin("OMCurrencyModule", OMEconomy.OMBase.OMBaseModule.MODULE_VERSION)]
[assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
namespace OMEconomy.OMCurrency
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OMCurrencyModule")]
public class OMCurrencyModule : IMoneyModule, ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string MODULE_VERSION = OMBase.OMBaseModule.MODULE_VERSION;
private string MODULE_NAME = "OMCURRENCY";
Boolean Enabled = false;
CommunicationHelpers m_communication = null;
public SceneHandler m_sceneHandler = SceneHandler.getInstance();
public Dictionary<UUID, int> m_KnownClientFunds = new Dictionary<UUID, int>();
public OMBaseModule omBase = new OMBaseModule();
public event ObjectPaid OnObjectPaid;
#region ISharedRegion implementation
public string Name { get { return "OMCURRENCY"; } }
public void Initialise(IConfigSource config)
{
IConfig cfg = config.Configs["OpenMetaverseEconomy"];
if (cfg == null)
return;
Enabled = cfg.GetBoolean("enabled", Enabled);
if (!Enabled)
return;
m_communication = new CommunicationHelpers(config, MODULE_NAME, OMBase.OMBaseModule.MODULE_VERSION);
MainServer.Instance.AddXmlRPCHandler("OMCurrencyNotification", currencyNotify, false);
MainServer.Instance.AddXmlRPCHandler("getCurrencyQuote", getCurrencyQuote, false);
MainServer.Instance.AddXmlRPCHandler("buyCurrency", buyCurrency, false);
MainServer.Instance.AddXmlRPCHandler("preflightBuyLandPrep", preBuyLand);
MainServer.Instance.AddXmlRPCHandler("buyLandPrep", buyLand);
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
if (!Enabled)
return;
scene.RegisterModuleInterface<IMoneyModule>(this);
}
public void RegionLoaded(Scene scene)
{
if (!Enabled)
return;
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClientClosed += OnClientClosed;
scene.EventManager.OnValidateLandBuy += OnValidateLandBuy;
scene.EventManager.OnLandBuy += OnLandBuy;
m_communication.RegisterService(MODULE_NAME, OMBase.OMBaseModule.MODULE_VERSION, scene.RegionInfo.RegionID);
}
public Type ReplaceableInterface
{
get { return null; }
}
public void RemoveRegion(Scene scene)
{
if (!Enabled)
return;
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnClientClosed -= OnClientClosed;
scene.EventManager.OnValidateLandBuy -= OnValidateLandBuy;
scene.EventManager.OnLandBuy -= OnLandBuy;
scene.UnregisterModuleInterface<IMoneyModule>(this);
}
public void Close() { }
#endregion
#region // Not implemented
public bool GroupCreationCovered(IClientAPI client) { return true; }
public bool AmountCovered(UUID agentID, int amount) { return true; }
public bool UploadCovered(UUID agentID, int amount) { return true; }
public int UploadCharge { get { return 13; } }
public int GroupCreationCharge { get { return 12; } }
public void ApplyUploadCharge(UUID agentID, int second, string third) { }
public void ApplyGroupCreationCharge(UUID agentID) { }
public bool MoveMoney(UUID fromAgentID, UUID toAgentID, int amount,MoneyTransactionType type, string text)
{
return false;
}
public void MoveMoney(UUID fromAgentID, UUID toAgentID, int amount, string text)
{
}
//prior 0.7.6
//public void ApplyCharge(UUID agentID, int amount, string text) { }
//new since 0.7.6
public void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type) { }
public void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type, string extraData) { }
public void updateClientFunds(UUID clientUUID)
{
}
#endregion
public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, int amount, UUID txn, out string reason)
{
try
{
SceneObjectPart part = m_sceneHandler.FindPrim(objectID);
if (part == null)
{
throw new Exception("Could not find prim " + objectID);
}
Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
additionalParameters.Add("primUUID", part.UUID.ToString());
additionalParameters.Add("primName", part.Name);
additionalParameters.Add("primDescription", part.Description);
additionalParameters.Add("primLocation", m_sceneHandler.GetObjectLocation(part));
additionalParameters.Add("parentUUID", part.OwnerID.ToString());
DoMoneyTransfer(fromID, toID, amount, (int)TransactionType.OBJECT_PAYS, additionalParameters);
reason = String.Empty;
return true;
}
catch (Exception e)
{
m_log.ErrorFormat("[{0}]: ObjectGiveMoney Exception: {1} - {2}", Name, e.Message, e.StackTrace);
reason = e.Message;
return false;
}
}
public int GetBalance(UUID clientUUID)
{
lock (m_KnownClientFunds)
{
return m_KnownClientFunds.ContainsKey(clientUUID) ? m_KnownClientFunds[clientUUID] : 0;
}
}
#region // Events
private void OnNewClient(IClientAPI client)
{
client.OnMoneyBalanceRequest += SendMoneyBalance;
client.OnMoneyTransferRequest += OnMoneyTransferRequest;
client.OnRequestPayPrice += requestPayPrice;
client.OnObjectBuy += ObjectBuy;
client.OnLogout += OnLogout;
client.OnScriptAnswer += OnScriptAnswer;
}
private void OnClientClosed(UUID agentUUID, Scene scene)
{
lock (m_KnownClientFunds)
{
if (m_KnownClientFunds.ContainsKey(agentUUID))
{
m_KnownClientFunds.Remove(agentUUID);
}
}
IClientAPI client = m_sceneHandler.LocateClientObject(agentUUID);
if (client != null)
{
client.OnMoneyBalanceRequest -= SendMoneyBalance;
client.OnRequestPayPrice -= requestPayPrice;
client.OnScriptAnswer -= OnScriptAnswer;
client.OnObjectBuy -= ObjectBuy;
client.OnMoneyTransferRequest -= OnMoneyTransferRequest;
}
}
private void OnLogout(IClientAPI client)
{
OnClientClosed(client.AgentId, null);
}
private void OnScriptAnswer(IClientAPI remoteClient, UUID objectID, UUID itemID, int answer)
{
try
{
SceneObjectPart part = m_sceneHandler.FindPrim(objectID);
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("primUUID", part.UUID.ToString());
parameters.Add("primName", part.Name);
parameters.Add("primDescription", part.Description);
parameters.Add("primLocation", m_sceneHandler.GetObjectLocation(part));
parameters.Add("parentUUID", part.OwnerID.ToString());
parameters.Add("regionUUID", part.RegionID.ToString());
//parameters.Add("m_gridURL", m_gridURL);
if ((answer & 0x2) == 2)
{
parameters.Add("method", "allowPrimDebit");
}
else
{
parameters.Add("method", "removePrimDebit");
}
TaskInventoryItem item = null;
part.TaskInventory.TryGetValue(itemID, out item);
Dictionary<string, string[]> inventoryItems = new Dictionary<string, string[]>();
inventoryItems.Add(item.ItemID.ToString(), new string[] { answer.ToString(), item.Name });
parameters.Add("inventoryItems", JsonMapper.ToJson(inventoryItems));
m_communication.DoRequestDictionary(parameters);
}
catch (Exception e)
{
m_log.ErrorFormat("[{0}]: ScriptChangedEvent Exception: {1} - {2}", Name, e.Message, e.StackTrace);
}
}
private void OnMoneyTransferRequest(UUID sourceID, UUID destID, int amount, int transactionType, string description)
{
IClientAPI sender = m_sceneHandler.LocateClientObject(sourceID);
if (sender == null)
{
m_log.ErrorFormat("[{0}]: MoneyTransferRequest(): Could not find Avatar {1}:({2})",
Name, sourceID.ToString(), sender.Name);
return;
}
switch (transactionType)
{
case (int)TransactionType.PAY_OBJECT:
SceneObjectPart part = m_sceneHandler.FindPrim(destID);
if (part == null)
{
return;
}
string name = m_sceneHandler.ResolveAgentName(part.OwnerID);
if (String.IsNullOrEmpty(name))
{
name = m_sceneHandler.ResolveGroupName(part.OwnerID);
}
Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
additionalParameters.Add("primUUID", part.UUID.ToString());
additionalParameters.Add("primName", part.Name);
additionalParameters.Add("primDescription", part.Description);
additionalParameters.Add("primLocation", m_sceneHandler.GetObjectLocation(part));
DoMoneyTransfer(sourceID, part.OwnerID, amount, transactionType, additionalParameters);
break;
case (int)TransactionType.GIFT:
DoMoneyTransfer(sourceID, destID, amount, transactionType);
break;
default:
m_log.ErrorFormat("[{0}]: TransactionType {1} not specified.", Name, transactionType);
break;
}
}
private void OnValidateLandBuy(Object osender, EventManager.LandBuyArgs e)
{
e.economyValidated = false;
}
private void OnLandBuy(Object osender, EventManager.LandBuyArgs e)
{
Scene s = m_sceneHandler.LocateSceneClientIn(e.agentId);
if (e.economyValidated == false)
{
if (e.parcelPrice == 0)
{
e.economyValidated = true;
s.EventManager.TriggerLandBuy(osender, e);
}
else
{
ILandObject parcel = s.LandChannel.GetLandObject(e.parcelLocalID);
Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
additionalParameters.Add("final", e.final == true ? "1" : "0");
additionalParameters.Add("removeContribution", e.removeContribution == true ? "1" : "0");
additionalParameters.Add("parcelLocalID", e.parcelLocalID.ToString());
additionalParameters.Add("parcelName", parcel.LandData.Name);
additionalParameters.Add("transactionID", e.transactionID.ToString());
additionalParameters.Add("amountDebited", e.amountDebited.ToString());
additionalParameters.Add("authenticated", e.authenticated == true ? "1" : "0");
DoMoneyTransfer(e.agentId, e.parcelOwnerID, e.parcelPrice, (int)TransactionType.BUY_LAND, additionalParameters);
}
}
}
#endregion Event Handler
public void SendMoneyBalance(IClientAPI client, UUID agentID, UUID SessionID, UUID TransactionID)
{
if (client.AgentId == agentID && client.SessionId == SessionID)
{
int returnfunds = GetBalance(agentID);
//new since 0.7.6
client.SendMoneyBalance(
TransactionID, true, new byte[0], returnfunds, 0, UUID.Zero, false, UUID.Zero, false, 0, String.Empty);
//prior 0.7.6
//client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds);
}
}
public void DoMoneyTransfer(UUID sourceId, UUID destId, int amount, int transactiontype)
{
DoMoneyTransfer(sourceId, destId, amount, transactiontype, null);
}
public void DoMoneyTransfer(UUID sourceId, UUID destId, int amount,
int transactiontype, Dictionary<string, string> additionalParameters)
{
System.Threading.ThreadPool.QueueUserWorkItem(delegate {
IClientAPI recipient = m_sceneHandler.LocateClientObject(destId);
string recipientName = recipient == null ? destId.ToString() : recipient.FirstName + " " + recipient.LastName;
IClientAPI sender = m_sceneHandler.LocateClientObject(sourceId);
string senderName = sender == null ? sourceId.ToString() : sender.FirstName + " " + sender.LastName;
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("method", "transferMoney");
d.Add("senderUUID", sourceId.ToString());
d.Add("senderName", senderName);
d.Add("recipientUUID", destId.ToString());
d.Add("recipientName", recipientName);
d.Add("amount", amount.ToString());
d.Add("transactionType", transactiontype.ToString());
if (transactiontype == (int)TransactionType.OBJECT_PAYS)
{
d.Add("regionUUID", m_sceneHandler.LocateSceneClientIn(destId).RegionInfo.RegionID.ToString());
}
else
{
d.Add("regionUUID", m_sceneHandler.LocateSceneClientIn(sourceId).RegionInfo.RegionID.ToString());
}
//d.Add("m_gridURL", m_gridURL);
if (additionalParameters != null)
{
foreach (KeyValuePair<string, string> pair in additionalParameters)
{
d.Add(pair.Key, pair.Value);
}
}
if (m_communication.DoRequestDictionary(d) == null)
{
serviceNotAvailable(sourceId);
}
}, null);
}
#region Local Fund Management
private void SetBalance(UUID AgentID, Int32 balance)
{
lock (m_KnownClientFunds)
{
if (m_KnownClientFunds.ContainsKey(AgentID))
{
m_KnownClientFunds[AgentID] = balance;
}
else
{
m_KnownClientFunds.Add(AgentID, balance);
}
}
}
#endregion Local Fund Management
public void requestPayPrice(IClientAPI client, UUID objectID)
{
SceneObjectPart prim = m_sceneHandler.FindPrim(objectID);
if (prim != null)
{
SceneObjectPart root = prim.ParentGroup.RootPart;
client.SendPayPrice(objectID, root.PayPrice);
}
}
public void ObjectBuy(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID groupID, UUID categoryID, uint localID, byte saleType, int salePrice)
{
m_log.DebugFormat("User {0} buys object {1} for {2} OMC", agentID, localID, salePrice);
Scene s = m_sceneHandler.LocateSceneClientIn(remoteClient.AgentId);
SceneObjectPart part = s.GetSceneObjectPart(localID);
if (part == null)
{
remoteClient.SendAgentAlertMessage("Unable to buy now. The object can not be found.", false);
return;
}
if (salePrice == 0)
{
m_log.Debug ("Sale Price is 0");
IBuySellModule buyModule = s.RequestModuleInterface<IBuySellModule>();
if (buyModule != null)
{
m_log.Debug ("Call BuyObject if sale price is 0");
buyModule.BuyObject(remoteClient, categoryID, localID, saleType, salePrice);
}
else
{
throw new Exception("Could not find IBuySellModule");
}
}
else
{
Dictionary<string, string> buyObject = new Dictionary<string, string>();
buyObject.Add("categoryID", categoryID.ToString());
buyObject.Add("localID", Convert.ToString(localID));
buyObject.Add("saleType", saleType.ToString());
buyObject.Add("objectUUID", part.UUID.ToString());
buyObject.Add("objectName", part.Name);
buyObject.Add("objectDescription", part.Description);
buyObject.Add("objectLocation", m_sceneHandler.GetObjectLocation(part));
DoMoneyTransfer(remoteClient.AgentId, part.OwnerID, salePrice, (int)TransactionType.BUY_OBJECT, buyObject);
}
}
private void serviceNotAvailable(UUID avatarUUID)
{
string message = "The currency service is not available. Please try again later.";
m_sceneHandler.LocateClientObject(avatarUUID).SendBlueBoxMessage(UUID.Zero, String.Empty, message);
}
#region XML NOTIFICATIONS
public XmlRpcResponse currencyNotify(XmlRpcRequest request, IPEndPoint ep)
{
XmlRpcResponse r = new XmlRpcResponse ();
Hashtable requestData = m_communication.ValidateRequest(request);
if(requestData != null) {
string method = (string)requestData["method"];
switch (method)
{
case "notifyDeliverObject": r.Value = deliverObject(requestData);
break;
case "notifyOnObjectPaid": r.Value = onObjectPaid(requestData);
break;
case "notifyLandBuy": r.Value = landBuy(requestData);
break;
case "notifyChangePrimPermission": r.Value = changePrimPermissions(requestData);
break;
case "notifyBalanceUpdate": r.Value = balanceUpdate(requestData);
break;
case "notifyGetVersion": r.Value = GetVersion(requestData);
break;
default: m_log.ErrorFormat("[{0}]: Method {1} is not supported", Name, method);
break;
}
} else {
r.SetFault(-1, "Could not validate the request");
}
return r;
}
// 12 => {8, 4} 25 => {16, 8, 1} 127 => {64, 32, 16, 8, 4, 2, 1}
private List<int> sliceBits(int permissions)
{
string binaryString = Convert.ToString(permissions, 2);
List<int> returnValue = new List<int>();
for (int i = binaryString.Length; i > 0; i--)
{
if (binaryString[i - 1] == '1')
{
returnValue.Add((int)Math.Pow(2, binaryString.Length - i));
}
}
return returnValue;
}
private Hashtable changePrimPermissions(Hashtable requestData)
{
Hashtable rparms = new Hashtable();
try
{
UUID primUUID = UUID.Parse((string)requestData["primUUID"]);
SceneObjectPart part = m_sceneHandler.FindPrim(primUUID);
if (part == null)
{
throw new Exception("Could not find the requested prim");
}
string inventoryItemsString = (string)requestData["inventoryItems"];
Dictionary<string, string> inventoryItems = JsonMapper.ToObject<Dictionary<string, string>>(inventoryItemsString);
foreach (KeyValuePair<string, string> inventoryItem in inventoryItems)
{
if (inventoryItem.Value == "0")
{
part.RemoveScriptEvents(UUID.Parse(inventoryItem.Key));
}
else
{
part.SetScriptEvents(UUID.Parse(inventoryItem.Key), Convert.ToInt32(inventoryItem.Value));
}
}
rparms["success"] = true;
}
catch (Exception e)
{
m_log.ErrorFormat("[{0}]: changePrimPermissions() Exception: {1} - {2}", Name, e.Message, e.StackTrace);
rparms["success"] = false;
}
return rparms;
}
private Hashtable balanceUpdate(Hashtable requestData)
{
Hashtable rparms = new Hashtable();
try
{
UUID avatarUUID = UUID.Parse((string)requestData["avatarUUID"]);
Int32 balance = Int32.Parse((string)requestData["balance"]);
IClientAPI client = m_sceneHandler.LocateClientObject(avatarUUID);
if (client == null)
{
throw new Exception("Avatar " + avatarUUID.ToString() + " does not reside in this region");
}
SetBalance(client.AgentId, balance);
SendMoneyBalance(client, client.AgentId, client.SessionId, UUID.Zero);
rparms["success"] = true;
}
catch (Exception e)
{
m_log.ErrorFormat("[{0}]: balanceUpdate() Exception: {1} - {2}", Name, e.Message, e.StackTrace);
rparms["success"] = false;
}
return rparms;
}
private Hashtable landBuy(Hashtable requestData)
{
Hashtable rparms = new Hashtable();
rparms["success"] = false;
try
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("method", "buyLand");
d.Add("id", (string)requestData["id"]);
Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
if (response != null)
{
UUID agentID = UUID.Parse((string)response["senderUUID"]);
int parcelLocalID = int.Parse((string)response["parcelLocalID"]);
int transactionID = int.Parse((string)response["transactionID"]);
int amountDebited = int.Parse((string)response["amountDebited"]);
bool final = (string)response["final"] == "1" ? true : false;
bool authenticated = (string)response["authenticated"] == "1" ? true : false;
bool removeContribution = (string)response["removeContribution"] == "1" ? true : false;
UUID regionUUID = UUID.Parse(response["regionUUID"]);
Scene s = m_sceneHandler.GetSceneByUUID(regionUUID);
ILandObject parcel = s.LandChannel.GetLandObject(parcelLocalID);
UUID groupID = parcel.LandData.GroupID;
int parcelArea = parcel.LandData.Area;
int parcelPrice = parcel.LandData.SalePrice;
bool groupOwned = parcel.LandData.IsGroupOwned;
UUID parcelOwnerUUID = parcel.LandData.OwnerID;
EventManager.LandBuyArgs landbuyArguments =
new EventManager.LandBuyArgs(agentID, groupID, final, groupOwned, removeContribution,
parcelLocalID, parcelArea, parcelPrice, authenticated);
IClientAPI sender = m_sceneHandler.LocateClientObject(agentID);
if (sender != null)
{
landbuyArguments.amountDebited = amountDebited;
landbuyArguments.parcelOwnerID = parcelOwnerUUID;
landbuyArguments.transactionID = transactionID;
s.EventManager.TriggerValidateLandBuy(sender, landbuyArguments);
landbuyArguments.economyValidated = true;
s.EventManager.TriggerLandBuy(sender, landbuyArguments);
rparms["success"] = true;
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[{0}]: landBuy(...) Exception: {1} - {2}", Name, e.Message, e.StackTrace);
}
return rparms;
}
private Hashtable deliverObject(Hashtable requestData)
{
Hashtable rparms = new Hashtable();
rparms["success"] = false;
try
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("method", "deliverObject");
d.Add("id", (string)requestData["id"]);
Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
if (response != null && response["success"] == "TRUE" || response["success"] == "1")
{
UInt32 localID = UInt32.Parse(response["localID"]);
UUID receiverUUID = UUID.Parse(response["receiverUUID"]);
UUID categoryID = UUID.Parse(response["categoryID"]);
byte saleType = byte.Parse(response["saleType"]);
int salePrice = response.ContainsKey("salePrice") ? Int32.Parse(response["salePrice"]) : 0;
IClientAPI sender = m_sceneHandler.LocateClientObject(receiverUUID);
if (sender == null)
{
throw new Exception("Avatar " + receiverUUID.ToString() + " does not reside in this region");
}
Scene s = m_sceneHandler.LocateSceneClientIn(receiverUUID);
if (s == null)
{
throw new Exception("Could not find the receiver's current scene");
}
IBuySellModule buyModule = s.RequestModuleInterface<IBuySellModule>();
if (buyModule != null)
{
m_log.Debug("Call BuyObject from delicerObject");
buyModule.BuyObject(sender, categoryID, localID, saleType, salePrice);
}
else
{
throw new Exception("Could not find IBuySellModule");
}
rparms["success"] = true;
}
}
catch (Exception e)
{
m_log.ErrorFormat("[{0}]: deliverObject() Exception: {1} - {2}", Name, e.Message, e.StackTrace);
}
return rparms;
}
private Hashtable GetVersion(Hashtable requestData)
{
Hashtable rparms = new Hashtable();
rparms["version"] = MODULE_VERSION;
return rparms;
}
private Hashtable onObjectPaid(Hashtable requestData)
{
Hashtable rparms = new Hashtable();
rparms["success"] = false;
try
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("method", "objectPaid");
d.Add("id", (string)requestData["id"]);
Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
if (response != null)
{
UUID primUUID = UUID.Parse(response["primUUID"]);
UUID senderUUID = UUID.Parse(response["senderUUID"]);
Int32 amount = Int32.Parse(response["amount"]);
IClientAPI depositor = m_sceneHandler.LocateClientObject(senderUUID);
if (depositor == null)
{
throw new Exception("Avatar " + senderUUID.ToString() + " does not reside in this Region");
}
ObjectPaid HandlerOnObjectPaid = OnObjectPaid;
if (HandlerOnObjectPaid != null)
{
m_log.Debug("Trigger Object Payed");
HandlerOnObjectPaid(primUUID, senderUUID, amount);
}
else
{
m_log.Debug("No Trigger Object Payed");
}
rparms["success"] = true;
}
}
catch (Exception e)
{
m_log.Error("[OMCURRENCY]: onObjectPaid() " + e.Message);
}
return rparms;
}
public XmlRpcResponse buyCurrency(XmlRpcRequest request, IPEndPoint ep)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable returnresp = new Hashtable();
try
{
UUID avatarUUID = UUID.Parse((string)requestData["agentId"]);
int amount = (Int32)requestData["currencyBuy"];
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("method", "buyCurrency");
d.Add("avatarUUID", avatarUUID.ToString());
d.Add("amount", amount.ToString());
Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
if (response != null && response["success"] == "TRUE" || response["success"] == "1")
{
returnresp.Add("success", true);
}
else
{
throw new Exception();
}
}
catch (Exception)
{
returnresp.Add("success", false);
returnresp.Add("errorMessage", "Please visit virwox.com to transfer money");
returnresp.Add("errorURI", "http://www.virwox.com");
}
XmlRpcResponse returnval = new XmlRpcResponse();
returnval.Value = returnresp;
return returnval;
}
public XmlRpcResponse getCurrencyQuote(XmlRpcRequest request, IPEndPoint ep)
{
Hashtable requestData = (Hashtable)request.Params[0];
UUID agentId = UUID.Zero;
int amount = 0;
Hashtable quoteResponse = new Hashtable();
try
{
UUID.TryParse((string)requestData["agentId"], out agentId);
amount = (Int32)requestData["currencyBuy"];
int realAmount = amount / getExchangeRate() + 1;
amount = realAmount * getExchangeRate();
Hashtable currencyResponse = new Hashtable();
currencyResponse.Add("estimatedCost", realAmount * 100);
currencyResponse.Add("currencyBuy", amount);
quoteResponse.Add("success", true);
quoteResponse.Add("currency", currencyResponse);
quoteResponse.Add("confirm", "");
}
catch (Exception)
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("method", "getString");
d.Add("type", "chargeAccount");
d.Add("avatarUUID", (string)requestData["agentId"]);
Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
if (response != null)
{
quoteResponse.Add ("success", false);
quoteResponse.Add ("errorMessage", response ["errorMessage"]);
quoteResponse.Add ("errorURI", response ["errorURI"]);
}
else
{
quoteResponse.Add ("success", false);
}
}
XmlRpcResponse returnval = new XmlRpcResponse();
returnval.Value = quoteResponse;
return returnval;
}
public XmlRpcResponse preBuyLand(XmlRpcRequest request, IPEndPoint ep)
{
m_log.Error("preBuyLand(XmlRpcRequest request, IPEndPoint ep)");
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
Hashtable membershiplevels = new Hashtable();
ArrayList levels = new ArrayList();
Hashtable level = new Hashtable();
level.Add("id", "00000000-0000-0000-0000-000000000000");
level.Add("description", "");
levels.Add(level);
Hashtable landuse = new Hashtable();
landuse.Add("upgrade", true);
landuse.Add("action", "");
Hashtable currency = new Hashtable();
currency.Add("estimatedCost", 0);
Hashtable membership = new Hashtable();
membershiplevels.Add("upgrade", true);
membershiplevels.Add("action", "");
membershiplevels.Add("levels", membershiplevels);
retparam.Add("success", true); // Cannot buy now - overall message.
retparam.Add("currency", currency);
retparam.Add("membership", membership);
retparam.Add("landuse", landuse);
retparam.Add("confirm", "");
ret.Value = retparam;
return ret;
}
public XmlRpcResponse buyLand(XmlRpcRequest request, IPEndPoint ep)
{
m_log.Error("buyLand(XmlRpcRequest request, IPEndPoint ep)");
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
retparam.Add("success", true);
ret.Value = retparam;
return ret;
}
private int getExchangeRate()
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("method", "getExchangeRate");
Dictionary<string, string> response = m_communication.DoRequestDictionary(d);
if (response != null)
{
return int.Parse((string)response["currentExchangeRate"]);
}
else
{
m_log.Error("buyLand(XmlRpcRequest request, IPEndPoint ep)");
}
return 0;
}
#endregion XML NOTIFICATIONS
}
public enum TransactionType : int
{
BUY_OBJECT = 5000,
GIFT = 5001,
PAY_OBJECT = 5008,
OBJECT_PAYS = 5009,
BUY_LAND = 5013,
}
}
| |
// 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 Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public class ExpressionMetadataProviderTest
{
private string PrivateProperty { get; set; }
public static string StaticProperty { get; set; }
public string Field = "Hello";
[Fact]
public void FromLambdaExpression_GetsExpectedMetadata_ForIdentityExpression()
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<TestModel>(provider);
// Act
var explorer = ExpressionMetadataProvider.FromLambdaExpression(m => m, viewData, provider);
// Assert
Assert.NotNull(explorer);
Assert.NotNull(explorer.Metadata);
Assert.Equal(ModelMetadataKind.Type, explorer.Metadata.MetadataKind);
Assert.Equal(typeof(TestModel), explorer.ModelType);
Assert.Null(explorer.Model);
}
[Fact]
public void FromLambdaExpression_GetsExpectedMetadata_ForPropertyExpression()
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<TestModel>(provider);
// Act
var explorer = ExpressionMetadataProvider.FromLambdaExpression(m => m.SelectedCategory, viewData, provider);
// Assert
Assert.NotNull(explorer);
Assert.NotNull(explorer.Metadata);
Assert.Equal(ModelMetadataKind.Property, explorer.Metadata.MetadataKind);
Assert.Equal(typeof(Category), explorer.ModelType);
Assert.Null(explorer.Model);
}
[Fact]
public void FromLambdaExpression_GetsExpectedMetadata_ForIndexerExpression()
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<TestModel[]>(provider);
// Act
var explorer = ExpressionMetadataProvider.FromLambdaExpression(m => m[23], viewData, provider);
// Assert
Assert.NotNull(explorer);
Assert.NotNull(explorer.Metadata);
Assert.Equal(ModelMetadataKind.Type, explorer.Metadata.MetadataKind);
Assert.Equal(typeof(TestModel), explorer.ModelType);
Assert.Null(explorer.Model);
}
[Fact]
public void FromLambdaExpression_GetsExpectedMetadata_ForLongerExpression()
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<TestModel[]>(provider);
var index = 42;
// Act
var explorer = ExpressionMetadataProvider.FromLambdaExpression(
m => m[index].SelectedCategory.CategoryId,
viewData,
provider);
// Assert
Assert.NotNull(explorer);
Assert.NotNull(explorer.Metadata);
Assert.Equal(ModelMetadataKind.Property, explorer.Metadata.MetadataKind);
Assert.Equal(typeof(int), explorer.ModelType);
Assert.Null(explorer.Model);
}
[Fact]
public void FromLambdaExpression_SetsContainerAsExpected()
{
// Arrange
var myModel = new TestModel { SelectedCategory = new Category() };
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<TestModel>(provider);
viewData.Model = myModel;
// Act
var metadata = ExpressionMetadataProvider.FromLambdaExpression<TestModel, Category>(
model => model.SelectedCategory,
viewData,
provider);
// Assert
Assert.Same(myModel, metadata.Container.Model);
}
[Theory]
[InlineData(null, ModelMetadataKind.Type, typeof(TestModel))]
[InlineData("", ModelMetadataKind.Type, typeof(TestModel))]
[InlineData("SelectedCategory", ModelMetadataKind.Property, typeof(Category))]
[InlineData("SelectedCategory.CategoryName", ModelMetadataKind.Type, typeof(string))]
public void FromStringExpression_GetsExpectedMetadata(
string expression,
ModelMetadataKind expectedKind,
Type expectedType)
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<TestModel>(provider);
// Act
var explorer = ExpressionMetadataProvider.FromStringExpression(expression, viewData, provider);
// Assert
Assert.NotNull(explorer);
Assert.NotNull(explorer.Metadata);
Assert.Equal(expectedKind, explorer.Metadata.MetadataKind);
Assert.Equal(expectedType, explorer.ModelType);
Assert.Null(explorer.Model);
}
[Fact]
public void FromStringExpression_SetsContainerAsExpected()
{
// Arrange
var myModel = new TestModel { SelectedCategory = new Category() };
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<TestModel>(provider);
viewData["Object"] = myModel;
// Act
var metadata = ExpressionMetadataProvider.FromStringExpression("Object.SelectedCategory",
viewData,
provider);
// Assert
Assert.Same(myModel, metadata.Container.Model);
}
// A private property can't be found by the model metadata provider, so return the property's type
// as a best-effort mechanism.
[Fact]
public void FromLambdaExpression_ForPrivateProperty_ReturnsMetadataOfExpressionType()
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<ExpressionMetadataProviderTest>(provider);
// Act
var explorer = ExpressionMetadataProvider.FromLambdaExpression(
m => m.PrivateProperty,
viewData,
provider);
// Assert
Assert.NotNull(explorer);
Assert.NotNull(explorer.Metadata);
Assert.Equal(ModelMetadataKind.Type, explorer.Metadata.MetadataKind);
Assert.Equal(typeof(string), explorer.ModelType);
}
// A static property can't be found by the model metadata provider, so return the property's type
// as a best-effort mechanism.
[Fact]
public void FromLambdaExpression_ForStaticProperty_ReturnsMetadataOfExpressionType()
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<ExpressionMetadataProviderTest>(provider);
// Act
var explorer = ExpressionMetadataProvider.FromLambdaExpression(
m => ExpressionMetadataProviderTest.StaticProperty,
viewData,
provider);
// Assert
Assert.NotNull(explorer);
Assert.NotNull(explorer.Metadata);
Assert.Equal(ModelMetadataKind.Type, explorer.Metadata.MetadataKind);
Assert.Equal(typeof(string), explorer.ModelType);
}
// A field can't be found by the model metadata provider, so return the field's type
// as a best-effort mechanism.
[Fact]
public void FromLambdaExpression_ForField_ReturnsMetadataOfExpressionType()
{
// Arrange
var provider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary<ExpressionMetadataProviderTest>(provider);
// Act
var explorer = ExpressionMetadataProvider.FromLambdaExpression(
m => m.Field,
viewData,
provider);
// Assert
Assert.NotNull(explorer);
Assert.NotNull(explorer.Metadata);
Assert.Equal(ModelMetadataKind.Type, explorer.Metadata.MetadataKind);
Assert.Equal(typeof(string), explorer.ModelType);
}
private class TestModel
{
public Category SelectedCategory { get; set; }
}
private class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
}
}
| |
// ZlibBaseStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-August-06 21:22:38>
//
// ------------------------------------------------------------------
//
// This module defines the ZlibBaseStream class, which is an intnernal
// base class for DeflateStream, ZlibStream and GZipStream.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace EpLibrary.cs
{
internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 }
internal class ZlibBaseStream : System.IO.Stream
{
protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec();
protected internal StreamMode _streamMode = StreamMode.Undefined;
protected internal FlushType _flushMode;
protected internal ZlibStreamFlavor _flavor;
protected internal CompressionMode _compressionMode;
protected internal CompressionLevel _level;
protected internal bool _leaveOpen;
protected internal byte[] _workingBuffer;
protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault;
protected internal byte[] _buf1 = new byte[1];
protected internal System.IO.Stream _stream;
protected internal CompressionStrategy Strategy = CompressionStrategy.Default;
// workitem 7159
CRC32 crc;
protected internal string _GzipFileName;
protected internal string _GzipComment;
protected internal DateTime _GzipMtime;
protected internal int _gzipHeaderByteCount;
internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } }
public ZlibBaseStream(System.IO.Stream stream,
CompressionMode compressionMode,
CompressionLevel level,
ZlibStreamFlavor flavor,
bool leaveOpen)
: base()
{
this._flushMode = FlushType.None;
//this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT];
this._stream = stream;
this._leaveOpen = leaveOpen;
this._compressionMode = compressionMode;
this._flavor = flavor;
this._level = level;
// workitem 7159
if (flavor == ZlibStreamFlavor.GZIP)
{
this.crc = new CRC32();
}
}
protected internal bool _wantCompress
{
get
{
return (this._compressionMode == CompressionMode.Compress);
}
}
private ZlibCodec z
{
get
{
if (_z == null)
{
bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB);
_z = new ZlibCodec();
if (this._compressionMode == CompressionMode.Decompress)
{
_z.InitializeInflate(wantRfc1950Header);
}
else
{
_z.Strategy = Strategy;
_z.InitializeDeflate(this._level, wantRfc1950Header);
}
}
return _z;
}
}
private byte[] workingBuffer
{
get
{
if (_workingBuffer == null)
_workingBuffer = new byte[_bufferSize];
return _workingBuffer;
}
}
public override void Write(System.Byte[] buffer, int offset, int count)
{
// workitem 7159
// calculate the CRC on the unccompressed data (before writing)
if (crc != null)
crc.SlurpBlock(buffer, offset, count);
if (_streamMode == StreamMode.Undefined)
_streamMode = StreamMode.Writer;
else if (_streamMode != StreamMode.Writer)
throw new ZlibException("Cannot Write after Reading.");
if (count == 0)
return;
// first reference of z property will initialize the private var _z
z.InputBuffer = buffer;
_z.NextIn = offset;
_z.AvailableBytesIn = count;
bool done = false;
do
{
_z.OutputBuffer = workingBuffer;
_z.NextOut = 0;
_z.AvailableBytesOut = _workingBuffer.Length;
int rc = (_wantCompress)
? _z.Deflate(_flushMode)
: _z.Inflate(_flushMode);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message);
//if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
_stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
// If GZIP and de-compress, we're done when 8 bytes remain.
if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
}
while (!done);
}
private void finish()
{
if (_z == null) return;
if (_streamMode == StreamMode.Writer)
{
bool done = false;
do
{
_z.OutputBuffer = workingBuffer;
_z.NextOut = 0;
_z.AvailableBytesOut = _workingBuffer.Length;
int rc = (_wantCompress)
? _z.Deflate(FlushType.Finish)
: _z.Inflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
{
string verb = (_wantCompress ? "de" : "in") + "flating";
if (_z.Message == null)
throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc));
else
throw new ZlibException(verb + ": " + _z.Message);
}
if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
{
_stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
}
done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
// If GZIP and de-compress, we're done when 8 bytes remain.
if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
}
while (!done);
Flush();
// workitem 7159
if (_flavor == ZlibStreamFlavor.GZIP)
{
if (_wantCompress)
{
// Emit the GZIP trailer: CRC32 and size mod 2^32
int c1 = crc.Crc32Result;
_stream.Write(BitConverter.GetBytes(c1), 0, 4);
int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF);
_stream.Write(BitConverter.GetBytes(c2), 0, 4);
}
else
{
throw new ZlibException("Writing with decompression is not supported.");
}
}
}
// workitem 7159
else if (_streamMode == StreamMode.Reader)
{
if (_flavor == ZlibStreamFlavor.GZIP)
{
if (!_wantCompress)
{
// workitem 8501: handle edge case (decompress empty stream)
if (_z.TotalBytesOut == 0L)
return;
// Read and potentially verify the GZIP trailer:
// CRC32 and size mod 2^32
byte[] trailer = new byte[8];
// workitems 8679 & 12554
if (_z.AvailableBytesIn < 8)
{
// Make sure we have read to the end of the stream
Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn);
int bytesNeeded = 8 - _z.AvailableBytesIn;
int bytesRead = _stream.Read(trailer,
_z.AvailableBytesIn,
bytesNeeded);
if (bytesNeeded != bytesRead)
{
throw new ZlibException(String.Format("Missing or incomplete GZIP trailer. Expected 8 bytes, got {0}.",
_z.AvailableBytesIn + bytesRead));
}
}
else
{
Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length);
}
Int32 crc32_expected = BitConverter.ToInt32(trailer, 0);
Int32 crc32_actual = crc.Crc32Result;
Int32 isize_expected = BitConverter.ToInt32(trailer, 4);
Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF);
if (crc32_actual != crc32_expected)
throw new ZlibException(String.Format("Bad CRC32 in GZIP trailer. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected));
if (isize_actual != isize_expected)
throw new ZlibException(String.Format("Bad size in GZIP trailer. (actual({0})!=expected({1}))", isize_actual, isize_expected));
}
else
{
throw new ZlibException("Reading with compression is not supported.");
}
}
}
}
private void end()
{
if (z == null)
return;
if (_wantCompress)
{
_z.EndDeflate();
}
else
{
_z.EndInflate();
}
_z = null;
}
public override void Close()
{
if (_stream == null) return;
try
{
finish();
}
finally
{
end();
if (!_leaveOpen) _stream.Close();
_stream = null;
}
}
public override void Flush()
{
_stream.Flush();
}
public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
//_outStream.Seek(offset, origin);
}
public override void SetLength(System.Int64 value)
{
_stream.SetLength(value);
}
#if NOT
public int Read()
{
if (Read(_buf1, 0, 1) == 0)
return 0;
// calculate CRC after reading
if (crc!=null)
crc.SlurpBlock(_buf1,0,1);
return (_buf1[0] & 0xFF);
}
#endif
private bool nomoreinput = false;
private string ReadZeroTerminatedString()
{
var list = new System.Collections.Generic.List<byte>();
bool done = false;
do
{
// workitem 7740
int n = _stream.Read(_buf1, 0, 1);
if (n != 1)
throw new ZlibException("Unexpected EOF reading GZIP header.");
else
{
if (_buf1[0] == 0)
done = true;
else
list.Add(_buf1[0]);
}
} while (!done);
byte[] a = list.ToArray();
return GZipStream.iso8859dash1.GetString(a, 0, a.Length);
}
private int _ReadAndValidateGzipHeader()
{
int totalBytesRead = 0;
// read the header on the first read
byte[] header = new byte[10];
int n = _stream.Read(header, 0, header.Length);
// workitem 8501: handle edge case (decompress empty stream)
if (n == 0)
return 0;
if (n != 10)
throw new ZlibException("Not a valid GZIP stream.");
if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8)
throw new ZlibException("Bad GZIP header.");
Int32 timet = BitConverter.ToInt32(header, 4);
_GzipMtime = GZipStream._unixEpoch.AddSeconds(timet);
totalBytesRead += n;
if ((header[3] & 0x04) == 0x04)
{
// read and discard extra field
n = _stream.Read(header, 0, 2); // 2-byte length field
totalBytesRead += n;
Int16 extraLength = (Int16)(header[0] + header[1] * 256);
byte[] extra = new byte[extraLength];
n = _stream.Read(extra, 0, extra.Length);
if (n != extraLength)
throw new ZlibException("Unexpected end-of-file reading GZIP header.");
totalBytesRead += n;
}
if ((header[3] & 0x08) == 0x08)
_GzipFileName = ReadZeroTerminatedString();
if ((header[3] & 0x10) == 0x010)
_GzipComment = ReadZeroTerminatedString();
if ((header[3] & 0x02) == 0x02)
Read(_buf1, 0, 1); // CRC16, ignore
return totalBytesRead;
}
public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
{
// According to MS documentation, any implementation of the IO.Stream.Read function must:
// (a) throw an exception if offset & count reference an invalid part of the buffer,
// or if count < 0, or if buffer is null
// (b) return 0 only upon EOF, or if count = 0
// (c) if not EOF, then return at least 1 byte, up to <count> bytes
if (_streamMode == StreamMode.Undefined)
{
if (!this._stream.CanRead) throw new ZlibException("The stream is not readable.");
// for the first read, set up some controls.
_streamMode = StreamMode.Reader;
// (The first reference to _z goes through the private accessor which
// may initialize it.)
z.AvailableBytesIn = 0;
if (_flavor == ZlibStreamFlavor.GZIP)
{
_gzipHeaderByteCount = _ReadAndValidateGzipHeader();
// workitem 8501: handle edge case (decompress empty stream)
if (_gzipHeaderByteCount == 0)
return 0;
}
}
if (_streamMode != StreamMode.Reader)
throw new ZlibException("Cannot Read after Writing.");
if (count == 0) return 0;
if (nomoreinput && _wantCompress) return 0; // workitem 8557
if (buffer == null) throw new ArgumentNullException("buffer");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset");
if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count");
int rc = 0;
// set up the output of the deflate/inflate codec:
_z.OutputBuffer = buffer;
_z.NextOut = offset;
_z.AvailableBytesOut = count;
// This is necessary in case _workingBuffer has been resized. (new byte[])
// (The first reference to _workingBuffer goes through the private accessor which
// may initialize it.)
_z.InputBuffer = workingBuffer;
do
{
// need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any.
if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
{
// No data available, so try to Read data from the captive stream.
_z.NextIn = 0;
_z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
if (_z.AvailableBytesIn == 0)
nomoreinput = true;
}
// we have data in InputBuffer; now compress or decompress as appropriate
rc = (_wantCompress)
? _z.Deflate(_flushMode)
: _z.Inflate(_flushMode);
if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
return 0;
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message));
if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
break; // nothing more to read
}
//while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);
// workitem 8557
// is there more room in output?
if (_z.AvailableBytesOut > 0)
{
if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0)
{
// deferred
}
// are we completely done reading?
if (nomoreinput)
{
// and in compression?
if (_wantCompress)
{
// no more input data available; therefore we flush to
// try to complete the read
rc = _z.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message));
}
}
}
rc = (count - _z.AvailableBytesOut);
// calculate CRC after reading
if (crc != null)
crc.SlurpBlock(buffer, offset, rc);
return rc;
}
public override System.Boolean CanRead
{
get { return this._stream.CanRead; }
}
public override System.Boolean CanSeek
{
get { return this._stream.CanSeek; }
}
public override System.Boolean CanWrite
{
get { return this._stream.CanWrite; }
}
public override System.Int64 Length
{
get { return _stream.Length; }
}
public override long Position
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
internal enum StreamMode
{
Writer,
Reader,
Undefined,
}
public static void CompressString(String s, Stream compressor)
{
byte[] uncompressed = System.Text.Encoding.UTF8.GetBytes(s);
using (compressor)
{
compressor.Write(uncompressed, 0, uncompressed.Length);
}
}
public static void CompressBuffer(byte[] b, Stream compressor)
{
// workitem 8460
using (compressor)
{
compressor.Write(b, 0, b.Length);
}
}
public static String UncompressString(byte[] compressed, Stream decompressor)
{
// workitem 8460
byte[] working = new byte[1024];
var encoding = System.Text.Encoding.UTF8;
using (var output = new MemoryStream())
{
using (decompressor)
{
int n;
while ((n = decompressor.Read(working, 0, working.Length)) != 0)
{
output.Write(working, 0, n);
}
}
// reset to allow read from start
output.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(output, encoding);
return sr.ReadToEnd();
}
}
public static byte[] UncompressBuffer(byte[] compressed, Stream decompressor)
{
// workitem 8460
byte[] working = new byte[1024];
using (var output = new MemoryStream())
{
using (decompressor)
{
int n;
while ((n = decompressor.Read(working, 0, working.Length)) != 0)
{
output.Write(working, 0, n);
}
}
return output.ToArray();
}
}
}
}
| |
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
using Plang.Compiler.TypeChecker.AST;
using Plang.Compiler.TypeChecker.AST.Declarations;
using Plang.Compiler.Util;
namespace Plang.Compiler.TypeChecker
{
internal class DeclarationStubVisitor : PParserBaseVisitor<object>
{
private readonly ParseTreeProperty<IPDecl> nodesToDeclarations;
private readonly StackProperty<Scope> scope;
private DeclarationStubVisitor(
Scope globalScope,
ParseTreeProperty<IPDecl> nodesToDeclarations)
{
this.nodesToDeclarations = nodesToDeclarations;
scope = new StackProperty<Scope>(globalScope);
}
private Scope CurrentScope => scope.Value;
public static void PopulateStubs(
Scope globalScope,
PParser.ProgramContext context,
ParseTreeProperty<IPDecl> nodesToDeclarations)
{
DeclarationStubVisitor visitor = new DeclarationStubVisitor(globalScope, nodesToDeclarations);
visitor.Visit(context);
}
#region Events
public override object VisitEventDecl(PParser.EventDeclContext context)
{
string symbolName = context.name.GetText();
PEvent decl = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, decl);
CurrentScope.UniversalEventSet.AddEvent(decl);
return null;
}
#endregion Events
#region Event sets
public override object VisitEventSetDecl(PParser.EventSetDeclContext context)
{
string symbolName = context.name.GetText();
NamedEventSet decl = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, decl);
return null;
}
#endregion Event sets
#region Interfaces
public override object VisitInterfaceDecl(PParser.InterfaceDeclContext context)
{
string symbolName = context.name.GetText();
Interface decl = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, decl);
return null;
}
#endregion Interfaces
private object VisitChildrenWithNewScope(IHasScope decl, IRuleNode context)
{
using (scope.NewContext(CurrentScope.MakeChildScope()))
{
decl.Scope = CurrentScope;
return VisitChildren(context);
}
}
#region Typedefs
public override object VisitPTypeDef(PParser.PTypeDefContext context)
{
string symbolName = context.name.GetText();
TypeDef typeDef = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, typeDef);
return null;
}
public override object VisitForeignTypeDef(PParser.ForeignTypeDefContext context)
{
string symbolName = context.name.GetText();
TypeDef typeDef = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, typeDef);
return null;
}
#endregion Typedefs
#region Enum typedef
public override object VisitEnumTypeDefDecl(PParser.EnumTypeDefDeclContext context)
{
string symbolName = context.name.GetText();
PEnum pEnum = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, pEnum);
return VisitChildren(context);
}
public override object VisitEnumElem(PParser.EnumElemContext context)
{
string symbolName = context.name.GetText();
EnumElem elem = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, elem);
return null;
}
public override object VisitNumberedEnumElem(PParser.NumberedEnumElemContext context)
{
string symbolName = context.name.GetText();
EnumElem elem = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, elem);
return null;
}
#endregion Enum typedef
#region Machines
public override object VisitImplMachineDecl(PParser.ImplMachineDeclContext context)
{
string symbolName = context.name.GetText();
Machine decl = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, decl);
return VisitChildrenWithNewScope(decl, context);
}
public override object VisitSpecMachineDecl(PParser.SpecMachineDeclContext context)
{
string symbolName = context.name.GetText();
Machine decl = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, decl);
return VisitChildrenWithNewScope(decl, context);
}
public override object VisitVarDecl(PParser.VarDeclContext context)
{
foreach (PParser.IdenContext varName in context.idenList()._names)
{
Variable decl = CurrentScope.Put(varName.GetText(), varName, VariableRole.Field);
nodesToDeclarations.Put(varName, decl);
}
return null;
}
public override object VisitStateDecl(PParser.StateDeclContext context)
{
string symbolName = context.name.GetText();
AST.States.State decl = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, decl);
return null;
}
#endregion Machines
#region Functions
public override object VisitPFunDecl(PParser.PFunDeclContext context)
{
string symbolName = context.name.GetText();
Function decl = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, decl);
return VisitChildrenWithNewScope(decl, context);
}
public override object VisitFunParam(PParser.FunParamContext context)
{
string symbolName = context.name.GetText();
Variable decl = CurrentScope.Put(symbolName, context, VariableRole.Param);
nodesToDeclarations.Put(context, decl);
return null;
}
public override object VisitFunctionBody(PParser.FunctionBodyContext context)
{
return null;
}
public override object VisitForeignFunDecl(PParser.ForeignFunDeclContext context)
{
string symbolName = context.name.GetText();
Function decl = CurrentScope.Put(symbolName, context);
decl.Scope = CurrentScope.MakeChildScope();
nodesToDeclarations.Put(context, decl);
return VisitChildrenWithNewScope(decl, context);
}
#endregion Functions
#region Module System
public override object VisitNamedModuleDecl([NotNull] PParser.NamedModuleDeclContext context)
{
string symbolName = context.name.GetText();
NamedModule decl = CurrentScope.Put(symbolName, context);
nodesToDeclarations.Put(context, decl);
return null;
}
public override object VisitSafetyTestDecl([NotNull] PParser.SafetyTestDeclContext context)
{
string symbolName = context.testName.GetText();
SafetyTest decl = CurrentScope.Put(symbolName, context);
decl.Main = context.mainMachine?.GetText();
nodesToDeclarations.Put(context, decl);
return null;
}
public override object VisitRefinementTestDecl([NotNull] PParser.RefinementTestDeclContext context)
{
string symbolName = context.testName.GetText();
RefinementTest decl = CurrentScope.Put(symbolName, context);
decl.Main = context.mainMachine?.GetText();
nodesToDeclarations.Put(context, decl);
return null;
}
public override object VisitImplementationDecl([NotNull] PParser.ImplementationDeclContext context)
{
string symbolName = context.implName.GetText();
Implementation decl = CurrentScope.Put(symbolName, context);
decl.Main = context.mainMachine?.GetText();
nodesToDeclarations.Put(context, decl);
return null;
}
#endregion Module System
#region Tree clipping expressions
public override object VisitKeywordExpr(PParser.KeywordExprContext context)
{
return null;
}
public override object VisitSeqAccessExpr(PParser.SeqAccessExprContext context)
{
return null;
}
public override object VisitNamedTupleAccessExpr(PParser.NamedTupleAccessExprContext context)
{
return null;
}
public override object VisitPrimitiveExpr(PParser.PrimitiveExprContext context)
{
return null;
}
public override object VisitBinExpr(PParser.BinExprContext context)
{
return null;
}
public override object VisitUnaryExpr(PParser.UnaryExprContext context)
{
return null;
}
public override object VisitTupleAccessExpr(PParser.TupleAccessExprContext context)
{
return null;
}
public override object VisitUnnamedTupleExpr(PParser.UnnamedTupleExprContext context)
{
return null;
}
public override object VisitFunCallExpr(PParser.FunCallExprContext context)
{
return null;
}
public override object VisitCastExpr(PParser.CastExprContext context)
{
return null;
}
public override object VisitCtorExpr(PParser.CtorExprContext context)
{
return null;
}
public override object VisitParenExpr(PParser.ParenExprContext context)
{
return null;
}
public override object VisitNamedTupleExpr(PParser.NamedTupleExprContext context)
{
return null;
}
public override object VisitExpr(PParser.ExprContext context)
{
return null;
}
#endregion Tree clipping expressions
#region Tree clipping non-receive (containing) statements
public override object VisitRemoveStmt(PParser.RemoveStmtContext context)
{
return null;
}
public override object VisitPrintStmt(PParser.PrintStmtContext context)
{
return null;
}
public override object VisitSendStmt(PParser.SendStmtContext context)
{
return null;
}
public override object VisitCtorStmt(PParser.CtorStmtContext context)
{
return null;
}
public override object VisitAssignStmt(PParser.AssignStmtContext context)
{
return null;
}
public override object VisitAddStmt(PParser.AddStmtContext context)
{
return null;
}
public override object VisitInsertStmt(PParser.InsertStmtContext context)
{
return null;
}
public override object VisitAnnounceStmt(PParser.AnnounceStmtContext context)
{
return null;
}
public override object VisitRaiseStmt(PParser.RaiseStmtContext context)
{
return null;
}
public override object VisitFunCallStmt(PParser.FunCallStmtContext context)
{
return null;
}
public override object VisitNoStmt(PParser.NoStmtContext context)
{
return null;
}
public override object VisitGotoStmt(PParser.GotoStmtContext context)
{
return null;
}
public override object VisitAssertStmt(PParser.AssertStmtContext context)
{
return null;
}
public override object VisitReturnStmt(PParser.ReturnStmtContext context)
{
return null;
}
#endregion Tree clipping non-receive (containing) statements
#region Tree clipping types
public override object VisitSeqType(PParser.SeqTypeContext context)
{
return null;
}
public override object VisitNamedType(PParser.NamedTypeContext context)
{
return null;
}
public override object VisitTupleType(PParser.TupleTypeContext context)
{
return null;
}
public override object VisitNamedTupleType(PParser.NamedTupleTypeContext context)
{
return null;
}
public override object VisitPrimitiveType(PParser.PrimitiveTypeContext context)
{
return null;
}
public override object VisitMapType(PParser.MapTypeContext context)
{
return null;
}
public override object VisitSetType(PParser.SetTypeContext context)
{
return null;
}
public override object VisitType(PParser.TypeContext context)
{
return null;
}
public override object VisitIdenTypeList(PParser.IdenTypeListContext context)
{
return null;
}
public override object VisitIdenType(PParser.IdenTypeContext context)
{
return null;
}
public override object VisitTypeDefDecl(PParser.TypeDefDeclContext context)
{
return null;
}
#endregion Tree clipping types
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using System.IO;
using MonoMac.WebKit;
namespace Tomboy
{
public partial class MainWindowController : MonoMac.AppKit.NSWindowController
{
#region fields
/// <summary>
/// The Note Docuement which is contained in the Note Editor
/// </summary>
private DomDocument document;
private DomElement paraBlock;
public KeyboardListener keyboardListener = new KeyboardListener ();
public DomDocumentListener domDocumentListener = new DomDocumentListener ();
#endregion fields
#region Constructors
// Called when created from unmanaged code
public MainWindowController (IntPtr handle) : base (handle)
{
Initialize ();
}
// Called when created directly from a XIB file
[Export ("initWithCoder:")]
public MainWindowController (NSCoder coder) : base (coder)
{
Initialize ();
}
// Call to load from the XIB/NIB file
public MainWindowController () : base ("MainWindow")
{
Initialize ();
}
// Shared initialization code
void Initialize ()
{
}
#endregion
#region Actions
partial void NewNoteButton_Clicked (MonoMac.AppKit.NSButton sender)
{
NewNote ();
}
#endregion Actions
//strongly typed window accessor
public new MainWindow Window {
get {
return (MainWindow)base.Window;
}
}
// This method will be called automatically when the main window "wakes up".
[Export ("awakeFromNib:")]
public override void AwakeFromNib ()
{
tblNotes.Source = new TableNotesDataSource (tblNotes, searchField, noteWebView);
TableNotesDataSource.SelectedNoteChanged += delegate(Note note) {
loadNote (note);
};
KeyboardListener.NoteContentChanged += NoteContentChanged;
loadNoteWebKit ();
setTitle ("Tomboy");
noteWebView.OnFinishedLoading += delegate {
installKeyboardHandler ();
Console.WriteLine ("OnFinishedLoading");
};
noteWebView.FinishedLoad += delegate {
document = noteWebView.MainFrameDocument;
Console.WriteLine ("webView Finished loading");
};
this.Window.WillClose += delegate {
Console.WriteLine ("Will Close");
};
}
#region Private Methods
/// <summary>
/// Sets the title in the Note Editor View
/// </summary>
/// <param name='title'>
/// Title.
/// </param>
private void setTitle (String title)
{
mainWindow.Title = title;
}
private void NewNote ()
{
Note note = AppDelegate.NoteEngine.NewNote ();
note.Title = "New Note";
paraBlock = document.GetElementById("main_content");
paraBlock.TextContent = "Example Note";
setTitle (note.Title);
/* select the row that the new Note was added to.
* In TableNotesDataSource we assume and add the new Note to index 0 in the notes arraylist
*/
tblNotes.SelectRow (0, false);
/* Set the new row to the viewable row */
System.Drawing.PointF point = new System.Drawing.PointF (0, 0);
notesScrollView.ScrollPoint (point);
notesScrollView.ContentView.ScrollPoint (point);
/* Example of programmically making element editable
* ((DomHtmlElement)document.GetElementById("main_content")).
*/
}
/// <summary>
/// Handle Note content that changed
/// </summary>
private void NoteContentChanged ()
{
}
/// <summary>
/// Retrieves the active note content
/// </summary>
/// <returns>
/// The note content.
/// </returns>
private String ActiveNoteContent ()
{
DomElement block = document.GetElementById("main_content");
return block.InnerText;
}
// Install the click handler so we can capture changes to the note
private void installKeyboardHandler()
{
var dom = noteWebView.MainFrameDocument;
var element = dom.GetElementById ("body");
element.AddEventListener ("focusout", domDocumentListener, true);
element.AddEventListener ("blur", domDocumentListener, true);
element.AddEventListener ("keypress", keyboardListener, true);
}
/// <summary>
/// Loads the note into the WebKit view
/// </summary>
/// <param name='note'>
/// Note.
/// </param>
private void loadNote (Note note)
{
mainWindow.Title = note.Title;
paraBlock = document.GetElementById("main_content");
paraBlock.TextContent = note.Text;
}
/// <summary>
/// Loads the note web kit.
/// </summary>
private void loadNoteWebKit ()
{
// Configure webView to let JavaScript talk to this object.
noteWebView.WindowScriptObject.SetValueForKey(this, new NSString("MainWindowController"));
Console.WriteLine ("WindowScriptObject loaded");
/*
Notes:
1. In JavaScript, you can now talk to this object using "window.MainWindowController".
2. You must explicitly allow methods to be called from JavaScript;
See the "public static bool IsSelectorExcludedFromWebScript(MonoMac.ObjCRuntime.Selector aSelector)"
method below for an example.
3. The method on this class which we call from JavaScript is showMessage:
To call it from JavaScript, we use window.AppController.showMessage_() <-- NOTE colon becomes underscore!
For more on method-name translation, see:
http://developer.apple.com/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html#
*/
// Load the HTML document
var htmlPath = Path.Combine (NSBundle.MainBundle.ResourcePath, "note.html");
Console.WriteLine ("htmlPath {0}", htmlPath);
noteWebView.MainFrame.LoadRequest(new NSUrlRequest (new NSUrl (htmlPath)));
}
#endregion Private Methods
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using NPOI.Util;
/**
* Title: Extended Format Record
* Description: Probably one of the more complex records. There are two breeds:
* Style and Cell.
*
* It should be noted that fields in the extended format record are
* somewhat arbitrary. Almost all of the fields are bit-level, but
* we name them as best as possible by functional Group. In some
* places this Is better than others.
*
*
* REFERENCE: PG 426 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)
* @author Andrew C. Oliver (acoliver at apache dot org)
* @version 2.0-pre
*/
internal class ExtendedFormatRecord : StandardRecord
{
public const short sid = 0xE0;
// null constant
public const short NULL = unchecked((short)0xfff0);
// xf type
public const short XF_STYLE = 1;
public const short XF_CELL = 0;
// borders
public const short NONE = 0x0;
public const short THIN = 0x1;
public const short MEDIUM = 0x2;
public const short DASHED = 0x3;
public const short DOTTED = 0x4;
public const short THICK = 0x5;
public const short DOUBLE = 0x6;
public const short HAIR = 0x7;
public const short MEDIUM_DASHED = 0x8;
public const short DASH_DOT = 0x9;
public const short MEDIUM_DASH_DOT = 0xA;
public const short DASH_DOT_DOT = 0xB;
public const short MEDIUM_DASH_DOT_DOT = 0xC;
public const short SLANTED_DASH_DOT = 0xD;
// alignment
public const short GENERAL = 0x0;
public const short LEFT = 0x1;
public const short CENTER = 0x2;
public const short RIGHT = 0x3;
public const short FILL = 0x4;
public const short JUSTIFY = 0x5;
public const short CENTER_SELECTION = 0x6;
// vertical alignment
public const short VERTICAL_TOP = 0x0;
public const short VERTICAL_CENTER = 0x1;
public const short VERTICAL_BOTTOM = 0x2;
public const short VERTICAL_JUSTIFY = 0x3;
// fill
public const short NO_FILL = 0;
public const short SOLID_FILL = 1;
public const short FINE_DOTS = 2;
public const short ALT_BARS = 3;
public const short SPARSE_DOTS = 4;
public const short THICK_HORZ_BANDS = 5;
public const short THICK_VERT_BANDS = 6;
public const short THICK_BACKWARD_DIAG = 7;
public const short THICK_FORWARD_DIAG = 8;
public const short BIG_SPOTS = 9;
public const short BRICKS = 10;
public const short THIN_HORZ_BANDS = 11;
public const short THIN_VERT_BANDS = 12;
public const short THIN_BACKWARD_DIAG = 13;
public const short THIN_FORWARD_DIAG = 14;
public const short SQUARES = 15;
public const short DIAMONDS = 16;
// fields in BOTH style and Cell XF records
private short field_1_font_index; // not bit-mapped
private short field_2_format_index; // not bit-mapped
// field_3_cell_options bit map
static private BitField _locked = BitFieldFactory.GetInstance(0x0001);
static private BitField _hidden = BitFieldFactory.GetInstance(0x0002);
static private BitField _xf_type = BitFieldFactory.GetInstance(0x0004);
static private BitField _123_prefix = BitFieldFactory.GetInstance(0x0008);
static private BitField _parent_index = BitFieldFactory.GetInstance(0xFFF0);
private short field_3_cell_options;
// field_4_alignment_options bit map
static private BitField _alignment = BitFieldFactory.GetInstance(0x0007);
static private BitField _wrap_text = BitFieldFactory.GetInstance(0x0008);
static private BitField _vertical_alignment = BitFieldFactory.GetInstance(0x0070);
static private BitField _justify_last = BitFieldFactory.GetInstance(0x0080);
static private BitField _rotation = BitFieldFactory.GetInstance(0xFF00);
private short field_4_alignment_options;
// field_5_indention_options
static private BitField _indent =
BitFieldFactory.GetInstance(0x000F);
static private BitField _shrink_to_fit =
BitFieldFactory.GetInstance(0x0010);
static private BitField _merge_cells =
BitFieldFactory.GetInstance(0x0020);
static private BitField _Reading_order =
BitFieldFactory.GetInstance(0x00C0);
// apparently bits 8 and 9 are Unused
static private BitField _indent_not_parent_format =
BitFieldFactory.GetInstance(0x0400);
static private BitField _indent_not_parent_font =
BitFieldFactory.GetInstance(0x0800);
static private BitField _indent_not_parent_alignment =
BitFieldFactory.GetInstance(0x1000);
static private BitField _indent_not_parent_border =
BitFieldFactory.GetInstance(0x2000);
static private BitField _indent_not_parent_pattern =
BitFieldFactory.GetInstance(0x4000);
static private BitField _indent_not_parent_cell_options =
BitFieldFactory.GetInstance(0x8000);
private short field_5_indention_options;
// field_6_border_options bit map
static private BitField _border_left = BitFieldFactory.GetInstance(0x000F);
static private BitField _border_right = BitFieldFactory.GetInstance(0x00F0);
static private BitField _border_top = BitFieldFactory.GetInstance(0x0F00);
static private BitField _border_bottom = BitFieldFactory.GetInstance(0xF000);
private short field_6_border_options;
// all three of the following attributes are palette options
// field_7_palette_options bit map
static private BitField _left_border_palette_idx =
BitFieldFactory.GetInstance(0x007F);
static private BitField _right_border_palette_idx =
BitFieldFactory.GetInstance(0x3F80);
static private BitField _diag =
BitFieldFactory.GetInstance(0xC000);
private short field_7_palette_options;
// field_8_adtl_palette_options bit map
static private BitField _top_border_palette_idx =
BitFieldFactory.GetInstance(0x0000007F);
static private BitField _bottom_border_palette_idx =
BitFieldFactory.GetInstance(0x00003F80);
static private BitField _adtl_diag =
BitFieldFactory.GetInstance(0x001fc000);
static private BitField _adtl_diag_line_style =
BitFieldFactory.GetInstance(0x01e00000);
// apparently bit 25 Is Unused
static private BitField _adtl_Fill_pattern =
BitFieldFactory.GetInstance(unchecked((int)0xfc000000));
private int field_8_adtl_palette_options; // Additional to avoid 2
// field_9_fill_palette_options bit map
static private BitField _fill_foreground = BitFieldFactory.GetInstance(0x007F);
static private BitField _fill_background = BitFieldFactory.GetInstance(0x3f80);
// apparently bits 15 and 14 are Unused
private short field_9_fill_palette_options;
/**
* Constructor ExtendedFormatRecord
*
*
*/
public ExtendedFormatRecord()
{
}
/**
* Constructs an ExtendedFormat record and Sets its fields appropriately.
* @param in the RecordInputstream to Read the record from
*/
public ExtendedFormatRecord(RecordInputStream in1)
{
field_1_font_index = in1.ReadShort();
field_2_format_index = in1.ReadShort();
field_3_cell_options = in1.ReadShort();
field_4_alignment_options = in1.ReadShort();
field_5_indention_options = in1.ReadShort();
field_6_border_options = in1.ReadShort();
field_7_palette_options = in1.ReadShort();
field_8_adtl_palette_options = in1.ReadInt();
field_9_fill_palette_options = in1.ReadShort();
}
/**
* Clones all the style information from another
* ExtendedFormatRecord, onto this one. This
* will then hold all the same style options.
*
* If The source ExtendedFormatRecord comes from
* a different Workbook, you will need to sort
* out the font and format indicies yourself!
*/
public void CloneStyleFrom(ExtendedFormatRecord source)
{
field_1_font_index = source.field_1_font_index;
field_2_format_index = source.field_2_format_index;
field_3_cell_options = source.field_3_cell_options;
field_4_alignment_options = source.field_4_alignment_options;
field_5_indention_options = source.field_5_indention_options;
field_6_border_options = source.field_6_border_options;
field_7_palette_options = source.field_7_palette_options;
field_8_adtl_palette_options = source.field_8_adtl_palette_options;
field_9_fill_palette_options = source.field_9_fill_palette_options;
}
/// <summary>
/// Get the index to the FONT record (which font to use 0 based)
/// </summary>
public short FontIndex
{
get { return field_1_font_index; }
set { field_1_font_index = value; }
}
/// <summary>
/// Get the index to the Format record (which FORMAT to use 0-based)
/// </summary>
public short FormatIndex
{
get
{
return field_2_format_index;
}
set { field_2_format_index = value; }
}
/// <summary>
/// Gets the options bitmask - you can also use corresponding option bit Getters
/// (see other methods that reference this one)
/// </summary>
public short CellOptions
{
get
{
return field_3_cell_options;
}
set { field_3_cell_options = value; }
}
/// <summary>
/// Get whether the cell Is locked or not
/// </summary>
public bool IsLocked
{
get
{
return _locked.IsSet(field_3_cell_options);
}
set
{
field_3_cell_options = _locked.SetShortBoolean(field_3_cell_options,
value);
}
}
/// <summary>
/// Get whether the cell Is hidden or not
/// </summary>
public bool IsHidden
{
get
{
return _hidden.IsSet(field_3_cell_options);
}
set
{
field_3_cell_options = _hidden.SetShortBoolean(field_3_cell_options,
value);
}
}
/// <summary>
/// Get whether the cell Is a cell or style XFRecord
/// </summary>
public short XFType
{
get
{
return _xf_type.GetShortValue(field_3_cell_options);
}
set
{
field_3_cell_options = _xf_type.SetShortValue(field_3_cell_options,
value);
}
}
/// <summary>
/// Get some old holdover from lotus 123. Who cares, its all over for Lotus.
/// RIP Lotus.
/// </summary>
public bool _123Prefix
{
get{
return _123_prefix.IsSet(field_3_cell_options);
}
set
{
field_3_cell_options =
_123_prefix.SetShortBoolean(field_3_cell_options, value);
}
}
/// <summary>
/// for cell XF types this Is the parent style (usually 0/normal). For
/// style this should be NULL.
/// </summary>
public short ParentIndex
{
get
{
return _parent_index.GetShortValue(field_3_cell_options);
}
set
{
field_3_cell_options =
_parent_index.SetShortValue(field_3_cell_options, value);
}
}
/// <summary>
/// Get the alignment options bitmask. See corresponding bitGetter methods
/// that reference this one.
/// </summary>
public short AlignmentOptions
{
get
{
return field_4_alignment_options;
}
set { field_4_alignment_options = value; }
}
/// <summary>
/// Get the horizontal alignment of the cell.
/// </summary>
public short Alignment
{
get
{
return _alignment.GetShortValue(field_4_alignment_options);
}
set
{
field_4_alignment_options =
_alignment.SetShortValue(field_4_alignment_options, value);
}
}
/// <summary>
/// Get whether to wrap the text in the cell
/// </summary>
public bool WrapText
{
get
{
return _wrap_text.IsSet(field_4_alignment_options);
}
set
{
field_4_alignment_options =
_wrap_text.SetShortBoolean(field_4_alignment_options, value);
}
}
/// <summary>
/// Get the vertical alignment of text in the cell
/// </summary>
public short VerticalAlignment
{
get
{
return _vertical_alignment.GetShortValue(field_4_alignment_options);
}
set
{
field_4_alignment_options =
_vertical_alignment.SetShortValue(field_4_alignment_options,
value);
}
}
/// <summary>
/// Docs just say this Is for far east versions.. (I'm guessing it
/// justifies for right-to-left Read languages)
/// </summary>
public short JustifyLast
{
get
{// for far east languages supported only for format always 0 for US
return _justify_last.GetShortValue(field_4_alignment_options);
}
set
{ // for far east languages supported only for format always 0 for US
field_4_alignment_options =
_justify_last.SetShortValue(field_4_alignment_options, value);
}
}
/// <summary>
/// Get the degree of rotation. (I've not actually seen this used anywhere)
/// </summary>
public short Rotation
{
get
{
return _rotation.GetShortValue(field_4_alignment_options);
}
set
{
field_4_alignment_options =
_rotation.SetShortValue(field_4_alignment_options, value);
}
}
/// <summary>
/// Get the indent options bitmask (see corresponding bit Getters that reference
/// this field)
/// </summary>
public short IndentionOptions
{
get
{
return field_5_indention_options;
}
set { field_5_indention_options = value; }
}
/// <summary>
/// Get indention (not sure of the Units, think its spaces)
/// </summary>
public short Indent
{
get
{
return _indent.GetShortValue(field_5_indention_options);
}
set
{
field_5_indention_options =
_indent.SetShortValue(field_5_indention_options, value);
}
}
/// <summary>
/// Get whether to shrink the text to fit
/// </summary>
public bool ShrinkToFit
{
get
{
return _shrink_to_fit.IsSet(field_5_indention_options);
}
set
{
field_5_indention_options =
_shrink_to_fit.SetShortBoolean(field_5_indention_options, value);
}
}
/// <summary>
/// Get whether to merge cells
/// </summary>
public bool MergeCells
{
get
{
return _merge_cells.IsSet(field_5_indention_options);
}
set
{
field_5_indention_options =
_merge_cells.SetShortBoolean(field_5_indention_options, value);
}
}
/// <summary>
/// Get the Reading order for far east versions (0 - Context, 1 - Left to right,
/// 2 - right to left) - We could use some help with support for the far east.
/// </summary>
public short ReadingOrder
{
get
{// only for far east always 0 in US
return _Reading_order.GetShortValue(field_5_indention_options);
}
set
{ // only for far east always 0 in US
field_5_indention_options =
_Reading_order.SetShortValue(field_5_indention_options, value);
}
}
/// <summary>
/// Get whether or not to use the format in this XF instead of the parent XF.
/// </summary>
public bool IsIndentNotParentFormat
{
get
{
return _indent_not_parent_format.IsSet(field_5_indention_options);
}
set
{
field_5_indention_options =
_indent_not_parent_format
.SetShortBoolean(field_5_indention_options, value);
}
}
/// <summary>
/// Get whether or not to use the font in this XF instead of the parent XF.
/// </summary>
public bool IsIndentNotParentFont
{
get
{
return _indent_not_parent_font.IsSet(field_5_indention_options);
}
set
{
field_5_indention_options =
_indent_not_parent_font.SetShortBoolean(field_5_indention_options,
value);
}
}
/// <summary>
/// Get whether or not to use the alignment in this XF instead of the parent XF.
/// </summary>
public bool IsIndentNotParentAlignment
{
get{return _indent_not_parent_alignment.IsSet(field_5_indention_options);}
set
{
field_5_indention_options =
_indent_not_parent_alignment
.SetShortBoolean(field_5_indention_options, value);
}
}
/// <summary>
/// Get whether or not to use the border in this XF instead of the parent XF.
/// </summary>
public bool IsIndentNotParentBorder
{
get { return _indent_not_parent_border.IsSet(field_5_indention_options); }
set
{
field_5_indention_options =
_indent_not_parent_border
.SetShortBoolean(field_5_indention_options, value);
}
}
/// <summary>
/// Get whether or not to use the pattern in this XF instead of the parent XF.
/// (foregrount/background)
/// </summary>
public bool IsIndentNotParentPattern
{
get { return _indent_not_parent_pattern.IsSet(field_5_indention_options); }
set
{
field_5_indention_options =
_indent_not_parent_pattern
.SetShortBoolean(field_5_indention_options, value);
}
}
/// <summary>
/// Get whether or not to use the locking/hidden in this XF instead of the parent XF.
/// </summary>
public bool IsIndentNotParentCellOptions
{
get
{
return _indent_not_parent_cell_options
.IsSet(field_5_indention_options);
}
set
{
field_5_indention_options =
_indent_not_parent_cell_options
.SetShortBoolean(field_5_indention_options, value);
}
}
/// <summary>
/// Get the border options bitmask (see the corresponding bit Getter methods
/// that reference back to this one)
/// </summary>
public short BorderOptions
{
get { return field_6_border_options; }
set { field_6_border_options = value; }
}
/// <summary>
/// Get the borderline style for the left border
/// </summary>
public short BorderLeft
{
get{return _border_left.GetShortValue(field_6_border_options);}
set
{
field_6_border_options =
_border_left.SetShortValue(field_6_border_options, value);
}
}
/// <summary>
/// Get the borderline style for the right border
/// </summary>
public short BorderRight
{
get{return _border_right.GetShortValue(field_6_border_options);}
set
{
field_6_border_options =
_border_right.SetShortValue(field_6_border_options, value);
}
}
/// <summary>
/// Get the borderline style for the top border
/// </summary>
public short BorderTop
{
get{return _border_top.GetShortValue(field_6_border_options);}
set {
field_6_border_options =_border_top.SetShortValue(field_6_border_options, value);
}
}
/// <summary>
/// Get the borderline style for the bottom border
/// </summary>
public short BorderBottom
{
get{return _border_bottom.GetShortValue(field_6_border_options);}
set {
field_6_border_options =_border_bottom.SetShortValue(field_6_border_options, value);
}
}
/// <summary>
/// Get the palette options bitmask (see the individual bit Getter methods that
/// reference this one)
/// </summary>
public short PaletteOptions
{
get{return field_7_palette_options;}
set { field_7_palette_options = value; }
}
/// <summary>
/// Get the palette index for the left border color
/// </summary>
public short LeftBorderPaletteIdx
{
get{return _left_border_palette_idx
.GetShortValue(field_7_palette_options);
}
set {
field_7_palette_options =
_left_border_palette_idx.SetShortValue(field_7_palette_options,
value);
}
}
/// <summary>
/// Get the palette index for the right border color
/// </summary>
public short RightBorderPaletteIdx
{
get{return _right_border_palette_idx
.GetShortValue(field_7_palette_options);
}
set
{
field_7_palette_options =
_right_border_palette_idx.SetShortValue(field_7_palette_options,
value);
}
}
/// <summary>
/// Not sure what this Is for (maybe Fill lines?) 1 = down, 2 = up, 3 = both, 0 for none..
/// </summary>
public short Diag
{
get{return _diag.GetShortValue(field_7_palette_options);}
set
{
field_7_palette_options = _diag.SetShortValue(field_7_palette_options,
value);
}
}
/// <summary>
/// Get the Additional palette options bitmask (see individual bit Getter methods
/// that reference this method)
/// </summary>
public int AdtlPaletteOptions
{
get{return field_8_adtl_palette_options;}
set { field_8_adtl_palette_options = value; }
}
/// <summary>
/// Get the palette index for the top border
/// </summary>
public short TopBorderPaletteIdx
{
get{return (short)_top_border_palette_idx
.GetValue(field_8_adtl_palette_options);}
set
{
field_8_adtl_palette_options =
_top_border_palette_idx.SetValue(field_8_adtl_palette_options,
value);
}
}
/// <summary>
/// Get the palette index for the bottom border
/// </summary>
public short BottomBorderPaletteIdx
{
get{return (short)_bottom_border_palette_idx
.GetValue(field_8_adtl_palette_options);
}
set
{
field_8_adtl_palette_options =
_bottom_border_palette_idx.SetValue(field_8_adtl_palette_options,
value);
}
}
/// <summary>
/// Get for diagonal borders
/// </summary>
public short AdtlDiag
{
get{return (short)_adtl_diag.GetValue(field_8_adtl_palette_options);}
set
{
field_8_adtl_palette_options =
_adtl_diag.SetValue(field_8_adtl_palette_options, value);
}
}
/// <summary>
/// Get the diagonal border line style
/// </summary>
public short AdtlDiagLineStyle
{
get{return (short)_adtl_diag_line_style
.GetValue(field_8_adtl_palette_options);}
set
{
field_8_adtl_palette_options =
_adtl_diag_line_style.SetValue(field_8_adtl_palette_options,
value);
}
}
/// <summary>
/// Get the Additional Fill pattern
/// </summary>
public short AdtlFillPattern
{
get{return (short)_adtl_Fill_pattern
.GetValue(field_8_adtl_palette_options);}
set
{
field_8_adtl_palette_options =
_adtl_Fill_pattern.SetValue(field_8_adtl_palette_options, value);
}
}
/// <summary>
/// Get the Fill palette options bitmask (see indivdual bit Getters that
/// reference this method)
/// </summary>
public short FillPaletteOptions
{
get{return field_9_fill_palette_options;}
set { field_9_fill_palette_options = value; }
}
/// <summary>
/// Get the foreground palette color index
/// </summary>
public short FillForeground
{
get{return _fill_foreground.GetShortValue(field_9_fill_palette_options);}
set
{
field_9_fill_palette_options =
_fill_foreground.SetShortValue(field_9_fill_palette_options,
value);
}
}
/// <summary>
/// Get the background palette color index
/// </summary>
public short FillBackground
{
get{return _fill_background.GetShortValue(field_9_fill_palette_options);}
set
{
field_9_fill_palette_options =
_fill_background.SetShortValue(field_9_fill_palette_options,
value);
}
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[EXTENDEDFORMAT]\n");
if (XFType == XF_STYLE)
{
buffer.Append(" STYLE_RECORD_TYPE\n");
}
else if (XFType == XF_CELL)
{
buffer.Append(" CELL_RECORD_TYPE\n");
}
buffer.Append(" .fontindex = ")
.Append(StringUtil.ToHexString(FontIndex)).Append("\n");
buffer.Append(" .formatindex = ")
.Append(StringUtil.ToHexString(FormatIndex)).Append("\n");
buffer.Append(" .celloptions = ")
.Append(StringUtil.ToHexString(CellOptions)).Append("\n");
buffer.Append(" .Islocked = ").Append(IsLocked)
.Append("\n");
buffer.Append(" .Ishidden = ").Append(IsHidden)
.Append("\n");
buffer.Append(" .recordtype= ")
.Append(StringUtil.ToHexString(XFType)).Append("\n");
buffer.Append(" .parentidx = ")
.Append(StringUtil.ToHexString(ParentIndex)).Append("\n");
buffer.Append(" .alignmentoptions= ")
.Append(StringUtil.ToHexString(AlignmentOptions)).Append("\n");
buffer.Append(" .alignment = ").Append(Alignment)
.Append("\n");
buffer.Append(" .wraptext = ").Append(WrapText)
.Append("\n");
buffer.Append(" .valignment= ")
.Append(StringUtil.ToHexString(VerticalAlignment)).Append("\n");
buffer.Append(" .justlast = ")
.Append(StringUtil.ToHexString(JustifyLast)).Append("\n");
buffer.Append(" .rotation = ")
.Append(StringUtil.ToHexString(Rotation)).Append("\n");
buffer.Append(" .indentionoptions= ")
.Append(StringUtil.ToHexString(IndentionOptions)).Append("\n");
buffer.Append(" .indent = ")
.Append(StringUtil.ToHexString(Indent)).Append("\n");
buffer.Append(" .shrinktoft= ").Append(ShrinkToFit)
.Append("\n");
buffer.Append(" .mergecells= ").Append(MergeCells)
.Append("\n");
buffer.Append(" .Readngordr= ")
.Append(StringUtil.ToHexString(ReadingOrder)).Append("\n");
buffer.Append(" .formatflag= ")
.Append(IsIndentNotParentFormat).Append("\n");
buffer.Append(" .fontflag = ")
.Append(IsIndentNotParentFont).Append("\n");
buffer.Append(" .prntalgnmt= ")
.Append(IsIndentNotParentAlignment).Append("\n");
buffer.Append(" .borderflag= ")
.Append(IsIndentNotParentBorder).Append("\n");
buffer.Append(" .paternflag= ")
.Append(IsIndentNotParentPattern).Append("\n");
buffer.Append(" .celloption= ")
.Append(IsIndentNotParentCellOptions).Append("\n");
buffer.Append(" .borderoptns = ")
.Append(StringUtil.ToHexString(BorderOptions)).Append("\n");
buffer.Append(" .lftln = ")
.Append(StringUtil.ToHexString(BorderLeft)).Append("\n");
buffer.Append(" .rgtln = ")
.Append(StringUtil.ToHexString(BorderRight)).Append("\n");
buffer.Append(" .topln = ")
.Append(StringUtil.ToHexString(BorderTop)).Append("\n");
buffer.Append(" .btmln = ")
.Append(StringUtil.ToHexString(BorderBottom)).Append("\n");
buffer.Append(" .paleteoptns = ")
.Append(StringUtil.ToHexString(PaletteOptions)).Append("\n");
buffer.Append(" .leftborder= ")
.Append(StringUtil.ToHexString(LeftBorderPaletteIdx))
.Append("\n");
buffer.Append(" .rghtborder= ")
.Append(StringUtil.ToHexString(RightBorderPaletteIdx))
.Append("\n");
buffer.Append(" .diag = ")
.Append(StringUtil.ToHexString(Diag)).Append("\n");
buffer.Append(" .paleteoptn2 = ")
.Append(StringUtil.ToHexString(AdtlPaletteOptions))
.Append("\n");
buffer.Append(" .topborder = ")
.Append(StringUtil.ToHexString(TopBorderPaletteIdx))
.Append("\n");
buffer.Append(" .botmborder= ")
.Append(StringUtil.ToHexString(BottomBorderPaletteIdx))
.Append("\n");
buffer.Append(" .adtldiag = ")
.Append(StringUtil.ToHexString(AdtlDiag)).Append("\n");
buffer.Append(" .diaglnstyl= ")
.Append(StringUtil.ToHexString(AdtlDiagLineStyle)).Append("\n");
buffer.Append(" .Fillpattrn= ")
.Append(StringUtil.ToHexString(AdtlFillPattern)).Append("\n");
buffer.Append(" .Fillpaloptn = ")
.Append(StringUtil.ToHexString(FillPaletteOptions))
.Append("\n");
buffer.Append(" .foreground= ")
.Append(StringUtil.ToHexString(FillForeground)).Append("\n");
buffer.Append(" .background= ")
.Append(StringUtil.ToHexString(FillBackground)).Append("\n");
buffer.Append("[/EXTENDEDFORMAT]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(FontIndex);
out1.WriteShort(FormatIndex);
out1.WriteShort(CellOptions);
out1.WriteShort(AlignmentOptions);
out1.WriteShort(IndentionOptions);
out1.WriteShort(BorderOptions);
out1.WriteShort(PaletteOptions);
out1.WriteInt(AdtlPaletteOptions);
out1.WriteShort(FillPaletteOptions);
}
protected override int DataSize
{
get { return 20; }
}
public override short Sid
{
get { return sid; }
}
public override int GetHashCode()
{
int prime = 31;
int result = 1;
result = prime * result + field_1_font_index;
result = prime * result + field_2_format_index;
result = prime * result + field_3_cell_options;
result = prime * result + field_4_alignment_options;
result = prime * result + field_5_indention_options;
result = prime * result + field_6_border_options;
result = prime * result + field_7_palette_options;
result = prime * result + field_8_adtl_palette_options;
result = prime * result + field_9_fill_palette_options;
return result;
}
/**
* Will consider two different records with the same
* contents as Equals, as the various indexes
* that matter are embedded in the records
*/
public override bool Equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (obj is ExtendedFormatRecord)
{
ExtendedFormatRecord other = (ExtendedFormatRecord)obj;
if (field_1_font_index != other.field_1_font_index)
return false;
if (field_2_format_index != other.field_2_format_index)
return false;
if (field_3_cell_options != other.field_3_cell_options)
return false;
if (field_4_alignment_options != other.field_4_alignment_options)
return false;
if (field_5_indention_options != other.field_5_indention_options)
return false;
if (field_6_border_options != other.field_6_border_options)
return false;
if (field_7_palette_options != other.field_7_palette_options)
return false;
if (field_8_adtl_palette_options != other.field_8_adtl_palette_options)
return false;
if (field_9_fill_palette_options != other.field_9_fill_palette_options)
return false;
return true;
}
return false;
}
}
}
| |
//
// 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.
//
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.DataFactories.Common.Models;
using Microsoft.Azure.Management.DataFactories.Models;
namespace Microsoft.Azure.Management.DataFactories
{
public static partial class HubOperationsExtensions
{
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public static HubCreateOrUpdateResponse BeginCreateOrUpdate(this IHubOperations operations, string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public static Task<HubCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete a hub instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginDelete(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).BeginDeleteAsync(resourceGroupName, dataFactoryName, hubName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a hub instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginDeleteAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName)
{
return operations.BeginDeleteAsync(resourceGroupName, dataFactoryName, hubName, CancellationToken.None);
}
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public static HubCreateOrUpdateResponse CreateOrUpdate(this IHubOperations operations, string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public static Task<HubCreateOrUpdateResponse> CreateOrUpdateAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the data factory hub to be created or updated.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public static HubCreateOrUpdateResponse CreateOrUpdateWithRawJsonContent(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName, HubCreateOrUpdateWithRawJsonContentParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, hubName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the data factory hub to be created or updated.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public static Task<HubCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName, HubCreateOrUpdateWithRawJsonContentParameters parameters)
{
return operations.CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, hubName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete a hub instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Delete(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).DeleteAsync(resourceGroupName, dataFactoryName, hubName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a hub instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> DeleteAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName)
{
return operations.DeleteAsync(resourceGroupName, dataFactoryName, hubName, CancellationToken.None);
}
/// <summary>
/// Gets a hub instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <returns>
/// The get hub operation response.
/// </returns>
public static HubGetResponse Get(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).GetAsync(resourceGroupName, dataFactoryName, hubName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a hub instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <returns>
/// The get hub operation response.
/// </returns>
public static Task<HubGetResponse> GetAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName)
{
return operations.GetAsync(resourceGroupName, dataFactoryName, hubName, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public static HubCreateOrUpdateResponse GetCreateOrUpdateStatus(this IHubOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).GetCreateOrUpdateStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public static Task<HubCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(this IHubOperations operations, string operationStatusLink)
{
return operations.GetCreateOrUpdateStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Gets the first page of data factory hub instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <returns>
/// The list hub operation response.
/// </returns>
public static HubListResponse List(this IHubOperations operations, string resourceGroupName, string dataFactoryName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).ListAsync(resourceGroupName, dataFactoryName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of data factory hub instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <returns>
/// The list hub operation response.
/// </returns>
public static Task<HubListResponse> ListAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName)
{
return operations.ListAsync(resourceGroupName, dataFactoryName, CancellationToken.None);
}
/// <summary>
/// Gets the next page of data factory hub instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next data factory hubs page.
/// </param>
/// <returns>
/// The list hub operation response.
/// </returns>
public static HubListResponse ListNext(this IHubOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IHubOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of data factory hub instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IHubOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next data factory hubs page.
/// </param>
/// <returns>
/// The list hub operation response.
/// </returns>
public static Task<HubListResponse> ListNextAsync(this IHubOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.IO;
using PlayFab.PfEditor.Json;
namespace PlayFab.PfEditor
{
[InitializeOnLoad]
public class PlayFabEditorHelper : UnityEditor.Editor
{
#region EDITOR_STRINGS
public static string EDEX_NAME = "PlayFab_EditorExtensions";
public static string EDEX_VERSION = "0.0.994";
public static string EDEX_ROOT = Application.dataPath + "/PlayFabEditorExtensions/Editor";
public static string DEV_API_ENDPOINT = "https://editor.playfabapi.com";
public static string TITLE_ENDPOINT = ".playfabapi.com";
public static string GAMEMANAGER_URL = "https://developer.playfab.com";
public static string PLAYFAB_SETTINGS_TYPENAME = "PlayFabSettings";
public static string PLAYFAB_EDEX_MAINFILE = "PlayFabEditor.cs";
public static string SDK_DOWNLOAD_PATH = "/Resources/PlayFabUnitySdk.unitypackage";
public static string EDEX_UPGRADE_PATH = "/Resources/PlayFabUnityEditorExtensions.unitypackage";
public static string EDEX_PACKAGES_PATH = "/Resources/MostRecentPackage.unitypackage";
public static string CLOUDSCRIPT_FILENAME = ".CloudScript.js"; //prefixed with a '.' to exclude this code from Unity's compiler
public static string CLOUDSCRIPT_PATH = EDEX_ROOT + "/Resources/" + CLOUDSCRIPT_FILENAME;
public static string ADMIN_API = "ENABLE_PLAYFABADMIN_API";
public static string SERVER_API = "ENABLE_PLAYFABSERVER_API";
public static string CLIENT_API = "DISABLE_PLAYFABCLIENT_API";
public static string DEBUG_REQUEST_TIMING = "PLAYFAB_REQUEST_TIMING";
public static string DISABLE_IDFA = "DISABLE_IDFA";
public static Dictionary<string, string> FLAG_LABELS = new Dictionary<string, string> {
{ ADMIN_API, "ENABLE CLIENT API" },
{ SERVER_API, "ENABLE ADMIN API" },
{ CLIENT_API, "ENABLE SERVER API" },
{ DEBUG_REQUEST_TIMING, "ENABLE REQUEST TIMES" },
{ DISABLE_IDFA, "ENABLE IDFA" },
};
public static Dictionary<string, bool> FLAG_INVERSION = new Dictionary<string, bool> {
{ ADMIN_API, true },
{ SERVER_API, false },
{ CLIENT_API, false },
{ DEBUG_REQUEST_TIMING, false },
{ DISABLE_IDFA, false },
};
public static string DEFAULT_SDK_LOCATION = "Assets/PlayFabSdk";
public static string STUDIO_OVERRIDE = "_OVERRIDE_";
public static string MSG_SPIN_BLOCK = "{\"useSpinner\":true, \"blockUi\":true }";
#endregion
private static GUISkin _uiStyle;
public static GUISkin uiStyle
{
get
{
if (_uiStyle != null)
return _uiStyle;
_uiStyle = GetUiStyle();
return _uiStyle;
}
}
static PlayFabEditorHelper()
{
// scan for changes to the editor folder / structure.
if (uiStyle == null)
{
string[] rootFiles = new string[0];
bool relocatedEdEx = false;
_uiStyle = null;
try
{
if (PlayFabEditorDataService.EnvDetails != null && !string.IsNullOrEmpty(PlayFabEditorDataService.EnvDetails.edexPath))
EDEX_ROOT = PlayFabEditorDataService.EnvDetails.edexPath;
rootFiles = Directory.GetDirectories(EDEX_ROOT);
}
catch
{
if (rootFiles.Length == 0)
{
// this probably means the editor folder was moved.
// see if we can locate the moved root and reload the assets
var movedRootFiles = Directory.GetFiles(Application.dataPath, PLAYFAB_EDEX_MAINFILE, SearchOption.AllDirectories);
if (movedRootFiles.Length > 0)
{
relocatedEdEx = true;
EDEX_ROOT = movedRootFiles[0].Substring(0, movedRootFiles[0].IndexOf(PLAYFAB_EDEX_MAINFILE) - 1);
PlayFabEditorDataService.EnvDetails.edexPath = EDEX_ROOT;
PlayFabEditorDataService.SaveEnvDetails();
}
}
}
finally
{
if (relocatedEdEx && rootFiles.Length == 0)
{
Debug.Log("Found new EdEx root: " + EDEX_ROOT);
}
else if (rootFiles.Length == 0)
{
Debug.Log("Could not relocate the PlayFab Editor Extension");
EDEX_ROOT = string.Empty;
}
}
}
}
private static GUISkin GetUiStyle()
{
var searchRoot = string.IsNullOrEmpty(EDEX_ROOT) ? Application.dataPath : EDEX_ROOT;
var pfGuiPaths = Directory.GetFiles(searchRoot, "PlayFabStyles.guiskin", SearchOption.AllDirectories);
foreach (var eachPath in pfGuiPaths)
{
var loadPath = eachPath.Substring(eachPath.IndexOf("Assets/"));
return (GUISkin)AssetDatabase.LoadAssetAtPath(loadPath, typeof(GUISkin));
}
return null;
}
public static void SharedErrorCallback(EditorModels.PlayFabError error)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error.ErrorMessage);
}
public static void SharedErrorCallback(string error)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error);
}
protected internal static EditorModels.PlayFabError GeneratePlayFabError(string json, object customData = null)
{
JsonObject errorDict = null;
Dictionary<string, List<string>> errorDetails = null;
try
{
//deserialize the error
errorDict = JsonWrapper.DeserializeObject<JsonObject>(json, PlayFabEditorUtil.ApiSerializerStrategy);
if (errorDict.ContainsKey("errorDetails"))
{
var ed = JsonWrapper.DeserializeObject<Dictionary<string, List<string>>>(errorDict["errorDetails"].ToString());
errorDetails = ed;
}
}
catch (Exception e)
{
return new EditorModels.PlayFabError()
{
ErrorMessage = e.Message
};
}
//create new error object
return new EditorModels.PlayFabError
{
HttpCode = errorDict.ContainsKey("code") ? Convert.ToInt32(errorDict["code"]) : 400,
HttpStatus = errorDict.ContainsKey("status")
? (string)errorDict["status"]
: "BadRequest",
Error = errorDict.ContainsKey("errorCode")
? (EditorModels.PlayFabErrorCode)Convert.ToInt32(errorDict["errorCode"])
: EditorModels.PlayFabErrorCode.ServiceUnavailable,
ErrorMessage = errorDict.ContainsKey("errorMessage")
? (string)errorDict["errorMessage"]
: string.Empty,
ErrorDetails = errorDetails,
CustomData = customData ?? new object()
};
}
#region unused, but could be useful
/// <summary>
/// Tool to create a color background texture
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="col"></param>
/// <returns>Texture2D</returns>
public static Texture2D MakeTex(int width, int height, Color col)
{
var pix = new Color[width * height];
for (var i = 0; i < pix.Length; i++)
pix[i] = col;
var result = new Texture2D(width, height);
result.SetPixels(pix);
result.Apply();
return result;
}
public static Vector3 GetColorVector(int colorValue)
{
return new Vector3((colorValue / 255f), (colorValue / 255f), (colorValue / 255f));
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole, Rob Prouse
//
// 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;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// ConstraintExpression represents a compound constraint in the
/// process of being constructed from a series of syntactic elements.
///
/// Individual elements are appended to the expression as they are
/// reorganized. When a constraint is appended, it is returned as the
/// value of the operation so that modifiers may be applied. However,
/// any partially built expression is attached to the constraint for
/// later resolution. When an operator is appended, the partial
/// expression is returned. If it's a self-resolving operator, then
/// a ResolvableConstraintExpression is returned.
/// </summary>
public class ConstraintExpression
{
#region Instance Fields
/// <summary>
/// The ConstraintBuilder holding the elements recognized so far
/// </summary>
protected readonly ConstraintBuilder builder;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ConstraintExpression"/> class.
/// </summary>
public ConstraintExpression() : this(new ConstraintBuilder())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ConstraintExpression"/>
/// class passing in a ConstraintBuilder, which may be pre-populated.
/// </summary>
/// <param name="builder">The builder.</param>
public ConstraintExpression(ConstraintBuilder builder)
{
Guard.ArgumentNotNull(builder, nameof(builder));
this.builder = builder;
}
#endregion
#region ToString()
/// <summary>
/// Returns a string representation of the expression as it
/// currently stands. This should only be used for testing,
/// since it has the side-effect of resolving the expression.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return builder.Resolve().ToString();
}
#endregion
#region Append Methods
/// <summary>
/// Appends an operator to the expression and returns the
/// resulting expression itself.
/// </summary>
public ConstraintExpression Append(ConstraintOperator op)
{
builder.Append(op);
return this;
}
/// <summary>
/// Appends a self-resolving operator to the expression and
/// returns a new ResolvableConstraintExpression.
/// </summary>
public ResolvableConstraintExpression Append(SelfResolvingOperator op)
{
builder.Append(op);
return new ResolvableConstraintExpression(builder);
}
/// <summary>
/// Appends a constraint to the expression and returns that
/// constraint, which is associated with the current state
/// of the expression being built. Note that the constraint
/// is not reduced at this time. For example, if there
/// is a NotOperator on the stack we don't reduce and
/// return a NotConstraint. The original constraint must
/// be returned because it may support modifiers that
/// are yet to be applied.
/// </summary>
public Constraint Append(Constraint constraint)
{
builder.Append(constraint);
return constraint;
}
#endregion
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression Not
{
get { return this.Append(new NotOperator()); }
}
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression No
{
get { return this.Append(new NotOperator()); }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public ConstraintExpression All
{
get { return this.Append(new AllOperator()); }
}
#endregion
#region Some
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if at least one of them succeeds.
/// </summary>
public ConstraintExpression Some
{
get { return this.Append(new SomeOperator()); }
}
#endregion
#region None
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them fail.
/// </summary>
public ConstraintExpression None
{
get { return this.Append(new NoneOperator()); }
}
#endregion
#region Exactly(n)
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding only if a specified number of them succeed.
/// </summary>
public ItemsConstraintExpression Exactly(int expectedCount)
{
builder.Append(new ExactCountOperator(expectedCount));
return new ItemsConstraintExpression(builder);
}
#endregion
#region One
/// <summary>
/// Returns a <see cref="ItemsConstraintExpression"/>, which will
/// apply the following constraint to a collection of length one, succeeding
/// only if exactly one of them succeeds.
/// </summary>
public ItemsConstraintExpression One
{
get
{
builder.Append(new ExactCountOperator(1));
return new ItemsConstraintExpression(builder);
}
}
#endregion
#region Property
/// <summary>
/// Returns a new PropertyConstraintExpression, which will either
/// test for the existence of the named property on the object
/// being tested or apply any following constraint to that property.
/// </summary>
public ResolvableConstraintExpression Property(string name)
{
return this.Append(new PropOperator(name));
}
#endregion
#region Length
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Length property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Length
{
get { return Property("Length"); }
}
#endregion
#region Count
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Count property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Count
{
get { return Property("Count"); }
}
#endregion
#region Message
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Message property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Message
{
get { return Property("Message"); }
}
#endregion
#region InnerException
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the InnerException property of the object being tested.
/// </summary>
public ResolvableConstraintExpression InnerException
{
get { return Property("InnerException"); }
}
#endregion
#region Attribute
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute(Type expectedType)
{
return this.Append(new AttributeOperator(expectedType));
}
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute<TExpected>()
{
return Attribute(typeof(TExpected));
}
#endregion
#region With
/// <summary>
/// With is currently a NOP - reserved for future use.
/// </summary>
public ConstraintExpression With
{
get { return this.Append(new WithOperator()); }
}
#endregion
#region Matches
/// <summary>
/// Returns the constraint provided as an argument - used to allow custom
/// custom constraints to easily participate in the syntax.
/// </summary>
public Constraint Matches(IResolveConstraint constraint)
{
return this.Append((Constraint)constraint.Resolve());
}
/// <summary>
/// Returns the constraint provided as an argument - used to allow custom
/// custom constraints to easily participate in the syntax.
/// </summary>
public Constraint Matches<TActual>(Predicate<TActual> predicate)
{
return this.Append(new PredicateConstraint<TActual>(predicate));
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public NullConstraint Null
{
get { return (NullConstraint)this.Append(new NullConstraint()); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public TrueConstraint True
{
get { return (TrueConstraint)this.Append(new TrueConstraint()); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public FalseConstraint False
{
get { return (FalseConstraint)this.Append(new FalseConstraint()); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public GreaterThanConstraint Positive
{
get { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(0)); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public LessThanConstraint Negative
{
get { return (LessThanConstraint)this.Append(new LessThanConstraint(0)); }
}
#endregion
#region Zero
/// <summary>
/// Returns a constraint that tests if item is equal to zero
/// </summary>
public EqualConstraint Zero
{
get { return (EqualConstraint)this.Append(new EqualConstraint(0)); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public NaNConstraint NaN
{
get { return (NaNConstraint)this.Append(new NaNConstraint()); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public EmptyConstraint Empty
{
get { return (EmptyConstraint)this.Append(new EmptyConstraint()); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public UniqueItemsConstraint Unique
{
get { return (UniqueItemsConstraint)this.Append(new UniqueItemsConstraint()); }
}
#endregion
#if SERIALIZATION
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public BinarySerializableConstraint BinarySerializable
{
get { return (BinarySerializableConstraint)this.Append(new BinarySerializableConstraint()); }
}
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in XML format.
/// </summary>
public XmlSerializableConstraint XmlSerializable
{
get { return (XmlSerializableConstraint)this.Append(new XmlSerializableConstraint()); }
}
#endif
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public EqualConstraint EqualTo(object expected)
{
return (EqualConstraint)this.Append(new EqualConstraint(expected));
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public SameAsConstraint SameAs(object expected)
{
return (SameAsConstraint)this.Append(new SameAsConstraint(expected));
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the supplied argument
/// </summary>
public GreaterThanConstraint GreaterThan(object expected)
{
return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(expected));
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected));
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint AtLeast(object expected)
{
return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected));
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the supplied argument
/// </summary>
public LessThanConstraint LessThan(object expected)
{
return (LessThanConstraint)this.Append(new LessThanConstraint(expected));
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected));
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint AtMost(object expected)
{
return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected));
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf(Type expectedType)
{
return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(expectedType));
}
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf<TExpected>()
{
return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(typeof(TExpected)));
}
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType));
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf<TExpected>()
{
return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(TExpected)));
}
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom(Type expectedType)
{
return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(expectedType));
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom<TExpected>()
{
return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(typeof(TExpected)));
}
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo(Type expectedType)
{
return (AssignableToConstraint)this.Append(new AssignableToConstraint(expectedType));
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo<TExpected>()
{
return (AssignableToConstraint)this.Append(new AssignableToConstraint(typeof(TExpected)));
}
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return (CollectionEquivalentConstraint)this.Append(new CollectionEquivalentConstraint(expected));
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return (CollectionSubsetConstraint)this.Append(new CollectionSubsetConstraint(expected));
}
#endregion
#region SupersetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a superset of the collection supplied as an argument.
/// </summary>
public CollectionSupersetConstraint SupersetOf(IEnumerable expected)
{
return (CollectionSupersetConstraint)this.Append(new CollectionSupersetConstraint(expected));
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public CollectionOrderedConstraint Ordered
{
get { return (CollectionOrderedConstraint)this.Append(new CollectionOrderedConstraint()); }
}
#endregion
#region Member
/// <summary>
/// Returns a new <see cref="SomeItemsConstraint"/> checking for the
/// presence of a particular object in the collection.
/// </summary>
public SomeItemsConstraint Member(object expected)
{
return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected)));
}
#endregion
#region Contains
/// <summary>
/// Returns a new <see cref="SomeItemsConstraint"/> checking for the
/// presence of a particular object in the collection.
/// </summary>
public SomeItemsConstraint Contains(object expected)
{
return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected)));
}
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contains(string expected)
{
return (ContainsConstraint)this.Append(new ContainsConstraint(expected));
}
/// <summary>
/// Returns a new <see cref="SomeItemsConstraint"/> checking for the
/// presence of a particular object in the collection.
/// </summary>
public SomeItemsConstraint Contain(object expected)
{
return Contains(expected);
}
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contain(string expected)
{
return Contains(expected);
}
#endregion
#region DictionaryContains
/// <summary>
/// Returns a new DictionaryContainsKeyConstraint checking for the
/// presence of a particular key in the Dictionary key collection.
/// </summary>
/// <param name="expected">The key to be matched in the Dictionary key collection</param>
public DictionaryContainsKeyConstraint ContainKey(object expected)
{
return (DictionaryContainsKeyConstraint)this.Append(new DictionaryContainsKeyConstraint(expected));
}
/// <summary>
/// Returns a new DictionaryContainsValueConstraint checking for the
/// presence of a particular value in the Dictionary value collection.
/// </summary>
/// <param name="expected">The value to be matched in the Dictionary value collection</param>
public DictionaryContainsValueConstraint ContainValue(object expected)
{
return (DictionaryContainsValueConstraint)this.Append(new DictionaryContainsValueConstraint(expected));
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint StringContaining(string expected)
{
return (SubstringConstraint)this.Append(new SubstringConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint ContainsSubstring(string expected)
{
return (SubstringConstraint)this.Append(new SubstringConstraint(expected));
}
#endregion
#region StartsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartWith(string expected)
{
return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartsWith(string expected)
{
return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.StartWith or StartsWith")]
public StartsWithConstraint StringStarting(string expected)
{
return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected));
}
#endregion
#region EndsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndWith(string expected)
{
return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndsWith(string expected)
{
return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.EndWith or EndsWith")]
public EndsWithConstraint StringEnding(string expected)
{
return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected));
}
#endregion
#region Matches
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Match(string pattern)
{
return (RegexConstraint)this.Append(new RegexConstraint(pattern));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Matches(string pattern)
{
return (RegexConstraint)this.Append(new RegexConstraint(pattern));
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Match or Matches")]
public RegexConstraint StringMatching(string pattern)
{
return (RegexConstraint)this.Append(new RegexConstraint(pattern));
}
#endregion
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public SamePathConstraint SamePath(string expected)
{
return (SamePathConstraint)this.Append(new SamePathConstraint(expected));
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the a subpath of the expected path after canonicalization.
/// </summary>
public SubPathConstraint SubPathOf(string expected)
{
return (SubPathConstraint)this.Append(new SubPathConstraint(expected));
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return (SamePathOrUnderConstraint)this.Append(new SamePathOrUnderConstraint(expected));
}
#endregion
#region InRange
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// inclusively within a specified range.
/// </summary>
/// <param name="from">Inclusive beginning of the range.</param>
/// <param name="to">Inclusive end of the range.</param>
public RangeConstraint InRange(object from, object to)
{
return (RangeConstraint)this.Append(new RangeConstraint(from, to));
}
#endregion
#region Exist
/// <summary>
/// Returns a constraint that succeeds if the value
/// is a file or directory and it exists.
/// </summary>
public Constraint Exist
{
get { return Append(new FileOrDirectoryExistsConstraint()); }
}
#endregion
#region AnyOf
/// <summary>
/// Returns a constraint that tests if an item is equal to any of parameters
/// </summary>
/// <param name="expected">Expected values</param>
public Constraint AnyOf(params object[] expected)
{
if (expected == null)
{
expected = new object[] { null };
}
return Append(new AnyOfConstraint(expected));
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Akka.Actor;
using Akka.Configuration;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Stage;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Akka.TestKit.Internal;
using Akka.TestKit.TestEvent;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
// ReSharper disable UnusedVariable
namespace Akka.Streams.Tests.Dsl
{
public class FlowSpec : AkkaSpec
{
private interface IFruit { };
private sealed class Apple : IFruit { };
private static IEnumerable<Apple> Apples() => Enumerable.Range(1, 1000).Select(_ => new Apple());
private static readonly Config Config = ConfigurationFactory.ParseString(@"
akka.actor.debug.receive=off
akka.loglevel=INFO
");
public ActorMaterializerSettings Settings { get; }
private ActorMaterializer Materializer { get; }
public FlowSpec(ITestOutputHelper helper) : base(Config.WithFallback(ConfigurationFactory.FromResource<ScriptedTest>("Akka.Streams.TestKit.Tests.reference.conf")), helper)
{
Settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2);
Materializer = ActorMaterializer.Create(Sys, Settings);
}
[Theory]
[InlineData("identity", 1)]
[InlineData("identity", 2)]
[InlineData("identity", 4)]
[InlineData("identity2", 1)]
[InlineData("identity2", 2)]
[InlineData("identity2", 4)]
public void A_flow_must_request_initial_elements_from_upstream(string name, int n)
{
ChainSetup<int, int, NotUsed> setup;
if (name.Equals("identity"))
setup = new ChainSetup<int, int, NotUsed>(Identity, Settings.WithInputBuffer(n, n),
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
else
setup = new ChainSetup<int, int, NotUsed>(Identity2, Settings.WithInputBuffer(n, n),
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, setup.Settings.MaxInputBufferSize);
}
[Fact]
public void A_Flow_must_request_more_elements_from_upstream_when_downstream_requests_more_elements()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings,
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, Settings.MaxInputBufferSize);
setup.DownstreamSubscription.Request(1);
setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
setup.DownstreamSubscription.Request(2);
setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
setup.UpstreamSubscription.SendNext("a");
setup.Downstream.ExpectNext("a");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
setup.UpstreamSubscription.SendNext("b");
setup.UpstreamSubscription.SendNext("c");
setup.UpstreamSubscription.SendNext("d");
setup.Downstream.ExpectNext("b");
setup.Downstream.ExpectNext("c");
}
[Fact]
public void A_Flow_must_deliver_events_when_publisher_sends_elements_and_then_completes()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings,
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.DownstreamSubscription.Request(1);
setup.UpstreamSubscription.SendNext("test");
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectNext("test");
setup.Downstream.ExpectComplete();
}
[Fact]
public void A_Flow_must_deliver_complete_signal_when_publisher_immediately_completes()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings,
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectComplete();
}
[Fact]
public void A_Flow_must_deliver_error_signal_when_publisher_immediately_fails()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings,
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
var weirdError = new Exception("weird test exception");
setup.UpstreamSubscription.SendError(weirdError);
setup.Downstream.ExpectError().Should().Be(weirdError);
}
[Fact]
public void A_Flow_must_cancel_upstream_when_single_subscriber_cancels_subscription_while_receiving_data()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this);
setup.DownstreamSubscription.Request(5);
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("test");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("test2");
setup.Downstream.ExpectNext("test");
setup.Downstream.ExpectNext("test2");
setup.DownstreamSubscription.Cancel();
// because of the "must cancel its upstream Subscription if its last downstream Subscription has been canceled" rule
setup.UpstreamSubscription.ExpectCancellation();
}
[Fact]
public void A_Flow_must_materialize_into_Publisher_Subscriber()
{
var flow = Flow.Create<string>();
var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer);
var flowIn = t.Item1;
var flowOut = t.Item2;
var c1 = this.CreateManualSubscriberProbe<string>();
flowOut.Subscribe(c1);
var source = Source.From(new[] {"1", "2", "3"}).RunWith(Sink.AsPublisher<string>(false), Materializer);
source.Subscribe(flowIn);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNext("1");
c1.ExpectNext("2");
c1.ExpectNext("3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_materialize_into_Publisher_Subscriber_and_transformation_processor()
{
var flow = Flow.Create<int>().Select(i=>i.ToString());
var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer);
var flowIn = t.Item1;
var flowOut = t.Item2;
var c1 = this.CreateManualSubscriberProbe<string>();
flowOut.Subscribe(c1);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
var source = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer);
source.Subscribe(flowIn);
c1.ExpectNext("1");
c1.ExpectNext("2");
c1.ExpectNext("3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_materialize_into_Publisher_Subscriber_and_multiple_transformation_processor()
{
var flow = Flow.Create<int>().Select(i => i.ToString()).Select(s => "elem-" + s);
var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer);
var flowIn = t.Item1;
var flowOut = t.Item2;
var c1 = this.CreateManualSubscriberProbe<string>();
flowOut.Subscribe(c1);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
var source = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer);
source.Subscribe(flowIn);
c1.ExpectNext("elem-1");
c1.ExpectNext("elem-2");
c1.ExpectNext("elem-3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_subscribe_Subscriber()
{
var flow = Flow.Create<string>();
var c1 = this.CreateManualSubscriberProbe<string>();
var sink = flow.To(Sink.FromSubscriber(c1));
var publisher = Source.From(new[] { "1", "2", "3" }).RunWith(Sink.AsPublisher<string>(false), Materializer);
Source.FromPublisher(publisher).To(sink).Run(Materializer);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNext("1");
c1.ExpectNext("2");
c1.ExpectNext("3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_perform_transformation_operation()
{
var flow = Flow.Create<int>().Select(i =>
{
TestActor.Tell(i.ToString());
return i.ToString();
});
var publisher = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer);
Source.FromPublisher(publisher).Via(flow).To(Sink.Ignore<string>()).Run(Materializer);
ExpectMsg("1");
ExpectMsg("2");
ExpectMsg("3");
}
[Fact]
public void A_Flow_must_perform_transformation_operation_and_subscribe_Subscriber()
{
var flow = Flow.Create<int>().Select(i => i.ToString());
var c1 = this.CreateManualSubscriberProbe<string>();
var sink = flow.To(Sink.FromSubscriber(c1));
var publisher = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer);
Source.FromPublisher(publisher).To(sink).Run(Materializer);
var sub1 = c1.ExpectSubscription();
sub1.Request(3);
c1.ExpectNext("1");
c1.ExpectNext("2");
c1.ExpectNext("3");
c1.ExpectComplete();
}
[Fact]
public void A_Flow_must_be_materializable_several_times_with_fanout_publisher()
{
this.AssertAllStagesStopped(() =>
{
var flow = Source.From(new[] {1, 2, 3}).Select(i => i.ToString());
var p1 = flow.RunWith(Sink.AsPublisher<string>(true), Materializer);
var p2 = flow.RunWith(Sink.AsPublisher<string>(true), Materializer);
var s1 = this.CreateManualSubscriberProbe<string>();
var s2 = this.CreateManualSubscriberProbe<string>();
var s3 = this.CreateManualSubscriberProbe<string>();
p1.Subscribe(s1);
p2.Subscribe(s2);
p2.Subscribe(s3);
var sub1 = s1.ExpectSubscription();
var sub2 = s2.ExpectSubscription();
var sub3 = s3.ExpectSubscription();
sub1.Request(3);
s1.ExpectNext("1");
s1.ExpectNext("2");
s1.ExpectNext("3");
s1.ExpectComplete();
sub2.Request(3);
sub3.Request(3);
s2.ExpectNext("1");
s2.ExpectNext("2");
s2.ExpectNext("3");
s2.ExpectComplete();
s3.ExpectNext("1");
s3.ExpectNext("2");
s3.ExpectNext("3");
s3.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Flow_must_be_covariant()
{
Source<IFruit, NotUsed> f1 = Source.From<IFruit>(Apples());
IPublisher<IFruit> p1 = Source.From<IFruit>(Apples()).RunWith(Sink.AsPublisher<IFruit>(false), Materializer);
SubFlow<IFruit, NotUsed, IRunnableGraph<NotUsed>> f2 =
Source.From<IFruit>(Apples()).SplitWhen(_ => true);
SubFlow<IFruit, NotUsed, IRunnableGraph<NotUsed>> f3 =
Source.From<IFruit>(Apples()).GroupBy(2, _ => true);
Source<Tuple<IImmutableList<IFruit>, Source<IFruit, NotUsed>>, NotUsed> f4 =
Source.From<IFruit>(Apples()).PrefixAndTail(1);
SubFlow<IFruit, NotUsed, Sink<string, NotUsed>> d1 =
Flow.Create<string>()
.Select<string, string, IFruit, NotUsed>(_ => new Apple())
.SplitWhen(_ => true);
SubFlow<IFruit, NotUsed, Sink<string, NotUsed>> d2 =
Flow.Create<string>()
.Select<string, string, IFruit, NotUsed>(_ => new Apple())
.GroupBy(-1,_ => 2);
Flow<string, Tuple<IImmutableList<IFruit>, Source<IFruit, NotUsed>>, NotUsed> d3 =
Flow.Create<string>().Select<string, string, IFruit, NotUsed>(_ => new Apple()).PrefixAndTail(1);
}
[Fact]
public void A_Flow_must_be_possible_to_convert_to_a_processor_and_should_be_able_to_take_a_Processor()
{
var identity1 = Flow.Create<int>().ToProcessor();
var identity2 = Flow.FromProcessor(() => identity1.Run(Materializer));
var task = Source.From(Enumerable.Range(1, 10))
.Via(identity2)
.Limit(100)
.RunWith(Sink.Seq<int>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1,10));
// Reusable:
task = Source.From(Enumerable.Range(1, 10))
.Via(identity2)
.Limit(100)
.RunWith(Sink.Seq<int>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_adapt_speed_to_the_currently_slowest_subscriber()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.DownstreamSubscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because initialInputBufferSize=1
setup.UpstreamSubscription.SendNext("firstElement");
setup.Downstream.ExpectNext("firstElement");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("element2");
setup.Downstream.ExpectNoMsg(TimeSpan.FromSeconds(1));
downstream2Subscription.Request(1);
downstream2.ExpectNext("firstElement");
setup.Downstream.ExpectNext("element2");
downstream2Subscription.Request(1);
downstream2.ExpectNext("element2");
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_support_slow_subscriber_with_fan_out_2()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 2), this);
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.DownstreamSubscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because initialInputBufferSize=1
setup.UpstreamSubscription.SendNext("element1");
setup.Downstream.ExpectNext("element1");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("element2");
setup.Downstream.ExpectNext("element2");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("element3");
// downstream2 has not requested anything, fan-out buffer 2
setup.Downstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100)));
downstream2Subscription.Request(2);
setup.Downstream.ExpectNext("element3");
downstream2.ExpectNext("element1");
downstream2.ExpectNext("element2");
downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100)));
setup.UpstreamSubscription.Request(1);
setup.UpstreamSubscription.SendNext("element4");
setup.Downstream.ExpectNext("element4");
downstream2Subscription.Request(2);
downstream2.ExpectNext("element3");
downstream2.ExpectNext("element4");
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectComplete();
downstream2.ExpectComplete();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_support_incoming_subscriber_while_elements_were_requested_before()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
setup.DownstreamSubscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a1");
setup.Downstream.ExpectNext("a1");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a2");
setup.Downstream.ExpectNext("a2");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
// link now while an upstream element is already requested
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
// situation here:
// downstream 1 now has 3 outstanding
// downstream 2 has 0 outstanding
setup.UpstreamSubscription.SendNext("a3");
setup.Downstream.ExpectNext("a3");
downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100))); // as nothing was requested yet, fanOutBox needs to cache element in this case
downstream2Subscription.Request(1);
downstream2.ExpectNext("a3");
// d1 now has 2 outstanding
// d2 now has 0 outstanding
// buffer should be empty so we should be requesting one new element
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because of buffer size 1
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_be_unblocked_when_blocking_subscriber_cancels_subscription()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.DownstreamSubscription.Request(5);
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("firstElement");
setup.Downstream.ExpectNext("firstElement");
downstream2Subscription.Request(1);
downstream2.ExpectNext("firstElement");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("element2");
setup.Downstream.ExpectNext("element2");
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext("element3");
setup.UpstreamSubscription.ExpectRequest(1);
setup.Downstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200)));
setup.Upstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200)));
downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200)));
// should unblock fanoutbox
downstream2Subscription.Cancel();
setup.Downstream.ExpectNext("element3");
setup.UpstreamSubscription.SendNext("element4");
setup.Downstream.ExpectNext("element4");
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectComplete();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_after_OnSubscribe_if_initial_upstream_was_completed()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
var downstream2 = this.CreateManualSubscriberProbe<string>();
// don't link it just yet
setup.DownstreamSubscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a1");
setup.Downstream.ExpectNext("a1");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a2");
setup.Downstream.ExpectNext("a2");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
// link now while an upstream element is already requested
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.UpstreamSubscription.SendNext("a3");
setup.UpstreamSubscription.SendComplete();
setup.Downstream.ExpectNext("a3");
setup.Downstream.ExpectComplete();
downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100))); // as nothing was requested yet, fanOutBox needs to cache element in this case
downstream2Subscription.Request(1);
downstream2.ExpectNext("a3");
downstream2.ExpectComplete();
var downstream3 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream3);
downstream3.ExpectSubscription();
downstream3.ExpectError().Should().BeOfType<NormalShutdownException>();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_should_be_called_instead_of_OnSubscribed_after_initial_upstream_reported_an_error()
{
var setup = new ChainSetup<int, string, NotUsed>(flow => flow.Select<int,int,string,NotUsed>(_ =>
{
throw new TestException("test");
}), Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 1), this);
setup.DownstreamSubscription.Request(1);
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.SendNext(5);
setup.UpstreamSubscription.ExpectRequest(1);
setup.UpstreamSubscription.ExpectCancellation();
setup.Downstream.ExpectError().Should().BeOfType<TestException>();
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
downstream2.ExpectSubscriptionAndError().Should().BeOfType<TestException>();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_when_all_subscriptions_were_cancelled ()
{
var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 16), this);
// make sure stream is initialized before canceling downstream
Thread.Sleep(100);
setup.UpstreamSubscription.ExpectRequest(1);
setup.DownstreamSubscription.Cancel();
setup.UpstreamSubscription.ExpectCancellation();
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
// IllegalStateException shut down
downstream2.ExpectSubscriptionAndError().Should().BeAssignableTo<IllegalStateException>();
}
[Fact]
public void A_Flow_with_multiple_subscribers_FanOutBox_should_be_created_from_a_function_easily()
{
Source.From(Enumerable.Range(0, 10))
.Via(Flow.FromFunction<int, int>(i => i + 1))
.RunWith(Sink.Seq<int>(), Materializer)
.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
}
[Fact]
public void A_broken_Flow_must_cancel_upstream_and_call_onError_on_current_and_future_downstream_subscribers_if_an_internal_error_occurs()
{
var setup = new ChainSetup<string, string, NotUsed>(FaultyFlow<string,string,string>, Settings.WithInputBuffer(1, 1),
(settings, factory) => ActorMaterializer.Create(factory, settings),
(source, materializer) => ToFanoutPublisher(source, materializer, 16), this);
Action<TestSubscriber.ManualProbe<string>> checkError = sprobe =>
{
var error = sprobe.ExpectError();
error.Should().BeOfType<AbruptTerminationException>();
error.Message.Should().StartWith("Processor actor");
};
var downstream2 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream2);
var downstream2Subscription = downstream2.ExpectSubscription();
setup.DownstreamSubscription.Request(5);
downstream2Subscription.Request(5);
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a1");
setup.Downstream.ExpectNext("a1");
downstream2.ExpectNext("a1");
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a2");
setup.Downstream.ExpectNext("a2");
downstream2.ExpectNext("a2");
var filters = new EventFilterBase[]
{
new ErrorFilter(typeof(NullReferenceException)),
new ErrorFilter(typeof(IllegalStateException)),
new ErrorFilter(typeof(PostRestartException)),// This is thrown because we attach the dummy failing actor to toplevel
};
try
{
Sys.EventStream.Publish(new Mute(filters));
setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1);
setup.UpstreamSubscription.SendNext("a3");
setup.UpstreamSubscription.ExpectCancellation();
// IllegalStateException terminated abruptly
checkError(setup.Downstream);
checkError(downstream2);
var downstream3 = this.CreateManualSubscriberProbe<string>();
setup.Publisher.Subscribe(downstream3);
downstream3.ExpectSubscription();
// IllegalStateException terminated abruptly
checkError(downstream3);
}
finally
{
Sys.EventStream.Publish(new Unmute(filters));
}
}
[Fact]
public void A_broken_Flow_must_suitably_override_attribute_handling_methods()
{
var f = Flow.Create<int>().Select(x => x + 1).Async().AddAttributes(Attributes.None).Named("name");
f.Module.Attributes.GetAttribute<Attributes.Name>().Value.Should().Be("name");
f.Module.Attributes.GetAttribute<Attributes.AsyncBoundary>()
.Should()
.Be(Attributes.AsyncBoundary.Instance);
}
[Fact]
public void A_broken_Flow_must_work_without_fusing()
{
var settings = ActorMaterializerSettings.Create(Sys).WithAutoFusing(false).WithInputBuffer(1, 1);
var noFusingMaterializer = ActorMaterializer.Create(Sys, settings);
// The map followed by a filter is to ensure that it is a CompositeModule passed in to Flow[Int].via(...)
var sink = Flow.Create<int>().Via(Flow.Create<int>().Select(i => i + 1).Where(_ => true))
.ToMaterialized(Sink.First<int>(), Keep.Right);
Source.Single(4711).RunWith(sink, noFusingMaterializer).AwaitResult().ShouldBe(4712);
}
private static Flow<TIn, TOut, TMat> Identity<TIn, TOut, TMat>(Flow<TIn, TOut, TMat> flow) => flow.Select(e => e);
private static Flow<TIn, TOut, TMat> Identity2<TIn, TOut, TMat>(Flow<TIn, TOut, TMat> flow) => Identity(flow);
private sealed class BrokenActorInterpreter : ActorGraphInterpreter
{
private readonly object _brokenMessage;
public BrokenActorInterpreter(GraphInterpreterShell shell, object brokenMessage) : base(shell)
{
_brokenMessage = brokenMessage;
}
protected override bool AroundReceive(Receive receive, object message)
{
var next = message as OnNext?;
if (next.HasValue && next.Value.Id == 0 && next.Value.Event == _brokenMessage)
throw new NullReferenceException($"I'm so broken {next.Value.Event}");
return base.AroundReceive(receive, message);
}
}
private Flow<TIn, TOut2, NotUsed> FaultyFlow<TIn, TOut, TOut2>(Flow<TIn, TOut, NotUsed> flow) where TOut : TOut2
{
Func<Flow<TOut, TOut2, NotUsed>> createGraph = () =>
{
var stage = new Select<TOut, TOut2>(x => x);
var assembly = new GraphAssembly(new IGraphStageWithMaterializedValue<Shape, object>[] { stage }, new[] { Attributes.None },
new Inlet[] { stage.Shape.Inlet , null}, new[] { 0, -1 }, new Outlet[] { null, stage.Shape.Outlet }, new[] { -1, 0 });
var t = assembly.Materialize(Attributes.None, assembly.Stages.Select(s => s.Module).ToArray(),
new Dictionary<IModule, object>(), _ => { });
var connections = t.Item1;
var logics = t.Item2;
var shell = new GraphInterpreterShell(assembly, connections, logics, stage.Shape, Settings,
(ActorMaterializerImpl) Materializer);
var props =
Props.Create(() => new BrokenActorInterpreter(shell, "a3"))
.WithDeploy(Deploy.Local)
.WithDispatcher("akka.test.stream-dispatcher");
var impl = Sys.ActorOf(props, "broken-stage-actor");
var subscriber = new ActorGraphInterpreter.BoundarySubscriber<TOut>(impl, shell, 0);
var publisher = new FaultyFlowPublisher<TOut2>(impl, shell);
impl.Tell(new ActorGraphInterpreter.ExposedPublisher(shell, 0, publisher));
return Flow.FromSinkAndSource(Sink.FromSubscriber(subscriber),
Source.FromPublisher(publisher));
};
return flow.Via(createGraph());
}
private sealed class FaultyFlowPublisher<TOut> : ActorPublisher<TOut>
{
public FaultyFlowPublisher(IActorRef impl, GraphInterpreterShell shell) : base(impl)
{
WakeUpMessage = new ActorGraphInterpreter.SubscribePending(shell, 0);
}
protected override object WakeUpMessage { get; }
}
private static IPublisher<TOut> ToPublisher<TOut, TMat>(Source<TOut, TMat> source,
ActorMaterializer materializer) => source.RunWith(Sink.AsPublisher<TOut>(false), materializer);
private static IPublisher<TOut> ToFanoutPublisher<TOut, TMat>(Source<TOut, TMat> source,
ActorMaterializer materializer, int elasticity)
=>
source.RunWith(
Sink.AsPublisher<TOut>(true).WithAttributes(Attributes.CreateInputBuffer(elasticity, elasticity)),
materializer);
private static Tuple<ISubscriber<TIn>, IPublisher<TOut>> MaterializeIntoSubscriberAndPublisher<TIn, TOut, TMat>(
Flow<TIn, TOut, TMat> flow, ActorMaterializer materializer)
=> flow.RunWith(Source.AsSubscriber<TIn>(), Sink.AsPublisher<TOut>(false), materializer);
}
}
| |
/*
* 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.
*/
// Uncomment to make asset Get requests for existing
// #define WAIT_ON_INPROGRESS_REQUESTS
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Timers;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
//[assembly: Addin("FlotsamAssetCache", "1.1")]
//[assembly: AddinDependency("OpenSim", "0.8.1")]
namespace OpenSim.Region.CoreModules.Asset
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")]
public class FlotsamAssetCache : ISharedRegionModule, IAssetCache, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled;
private bool m_timerRunning;
private bool m_cleanupRunning;
private const string m_ModuleName = "FlotsamAssetCache";
private const string m_DefaultCacheDirectory = "./assetcache";
private string m_CacheDirectory = m_DefaultCacheDirectory;
private readonly List<char> m_InvalidChars = new List<char>();
private int m_LogLevel = 0;
private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests
private static ulong m_Requests;
private static ulong m_RequestsForInprogress;
private static ulong m_DiskHits;
private static ulong m_MemoryHits;
private static ulong m_weakRefHits;
#if WAIT_ON_INPROGRESS_REQUESTS
private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>();
private int m_WaitOnInprogressTimeout = 3000;
#else
private HashSet<string> m_CurrentlyWriting = new HashSet<string>();
#endif
private bool m_FileCacheEnabled = true;
private ExpiringCache<string, AssetBase> m_MemoryCache;
private bool m_MemoryCacheEnabled = false;
private ExpiringCache<string, object> m_negativeCache;
private bool m_negativeCacheEnabled = true;
private bool m_negativeCacheSliding = false;
// Expiration is expressed in hours.
private double m_MemoryExpiration = 0.016;
private const double m_DefaultFileExpiration = 48;
// Negative cache is in seconds
private int m_negativeExpiration = 120;
private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration);
private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(1.0);
private static int m_CacheDirectoryTiers = 1;
private static int m_CacheDirectoryTierLen = 3;
private static int m_CacheWarnAt = 30000;
private System.Timers.Timer m_CacheCleanTimer;
private IAssetService m_AssetService;
private List<Scene> m_Scenes = new List<Scene>();
private object timerLock = new object();
private Dictionary<string,WeakReference> weakAssetReferences = new Dictionary<string, WeakReference>();
private object weakAssetReferencesLock = new object();
private bool m_updateFileTimeOnCacheHit = false;
public FlotsamAssetCache()
{
m_InvalidChars.AddRange(Path.GetInvalidPathChars());
m_InvalidChars.AddRange(Path.GetInvalidFileNameChars());
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return m_ModuleName; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetCaching", String.Empty);
if (name == Name)
{
m_MemoryCache = new ExpiringCache<string, AssetBase>();
m_negativeCache = new ExpiringCache<string, object>();
m_Enabled = true;
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
IConfig assetConfig = source.Configs["AssetCache"];
if (assetConfig == null)
{
m_log.Debug(
"[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults.");
}
else
{
m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled);
m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled);
m_MemoryExpiration = assetConfig.GetDouble("MemoryCacheTimeout", m_MemoryExpiration);
m_MemoryExpiration *= 3600.0; // config in hours to seconds
m_negativeCacheEnabled = assetConfig.GetBoolean("NegativeCacheEnabled", m_negativeCacheEnabled);
m_negativeExpiration = assetConfig.GetInt("NegativeCacheTimeout", m_negativeExpiration);
m_negativeCacheSliding = assetConfig.GetBoolean("NegativeCacheSliding", m_negativeCacheSliding);
m_updateFileTimeOnCacheHit = assetConfig.GetBoolean("UpdateFileTimeOnCacheHit", m_updateFileTimeOnCacheHit);
#if WAIT_ON_INPROGRESS_REQUESTS
m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000);
#endif
m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel);
m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay);
m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
m_FileExpirationCleanupTimer
= TimeSpan.FromHours(
assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours));
m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers);
m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen);
m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt);
}
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory);
if (m_CacheDirectoryTiers < 1)
{
m_CacheDirectoryTiers = 1;
}
else if (m_CacheDirectoryTiers > 3)
{
m_CacheDirectoryTiers = 3;
}
if (m_CacheDirectoryTierLen < 1)
{
m_CacheDirectoryTierLen = 1;
}
else if (m_CacheDirectoryTierLen > 4)
{
m_CacheDirectoryTierLen = 4;
}
MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache clear", "fcache clear [file] [memory]", "Remove all assets in the cache. If file or memory is specified then only this cache is cleared.", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand);
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
scene.RegisterModuleInterface<IAssetCache>(this);
m_Scenes.Add(scene);
}
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IAssetCache>(this);
m_Scenes.Remove(scene);
lock(timerLock)
{
if(m_timerRunning && m_Scenes.Count <= 0)
{
m_timerRunning = false;
m_CacheCleanTimer.Stop();
m_CacheCleanTimer.Close();
}
}
}
}
public void RegionLoaded(Scene scene)
{
if (m_Enabled)
{
if(m_AssetService == null)
m_AssetService = scene.RequestModuleInterface<IAssetService>();
lock(timerLock)
{
if(!m_timerRunning)
{
if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
{
m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds);
m_CacheCleanTimer.AutoReset = false;
m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
m_CacheCleanTimer.Start();
m_timerRunning = true;
}
}
}
if (m_MemoryCacheEnabled)
m_MemoryCache = new ExpiringCache<string, AssetBase>();
lock(weakAssetReferencesLock)
weakAssetReferences = new Dictionary<string, WeakReference>();
}
}
////////////////////////////////////////////////////////////
// IAssetCache
//
private void UpdateWeakReference(string key, AssetBase asset)
{
WeakReference aref = new WeakReference(asset);
lock(weakAssetReferencesLock)
weakAssetReferences[key] = aref;
}
private void UpdateMemoryCache(string key, AssetBase asset)
{
// NOTE DO NOT USE SLIDEEXPIRE option on current libomv
m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
}
private void UpdateFileCache(string key, AssetBase asset)
{
string filename = GetFileName(key);
try
{
// If the file is already cached, don't cache it, just touch it so access time is updated
if (File.Exists(filename))
{
UpdateFileLastAccessTime(filename);
}
else
{
// Once we start writing, make sure we flag that we're writing
// that object to the cache so that we don't try to write the
// same file multiple times.
lock (m_CurrentlyWriting)
{
#if WAIT_ON_INPROGRESS_REQUESTS
if (m_CurrentlyWriting.ContainsKey(filename))
{
return;
}
else
{
m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
}
#else
if (m_CurrentlyWriting.Contains(filename))
{
return;
}
else
{
m_CurrentlyWriting.Add(filename);
}
#endif
}
Util.FireAndForget(
delegate { WriteFileCache(filename, asset); }, null, "FlotsamAssetCache.UpdateFileCache");
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
asset.ID, e.Message, e.StackTrace);
}
}
public void Cache(AssetBase asset)
{
// TODO: Spawn this off to some seperate thread to do the actual writing
if (asset != null)
{
//m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
UpdateWeakReference(asset.ID, asset);
if (m_MemoryCacheEnabled)
UpdateMemoryCache(asset.ID, asset);
if (m_FileCacheEnabled)
UpdateFileCache(asset.ID, asset);
}
}
public void CacheNegative(string id)
{
if (m_negativeCacheEnabled)
{
if (m_negativeCacheSliding)
m_negativeCache.AddOrUpdate(id, null, TimeSpan.FromSeconds(m_negativeExpiration));
else
m_negativeCache.AddOrUpdate(id, null, m_negativeExpiration);
}
}
/// <summary>
/// Updates the cached file with the current time.
/// </summary>
/// <param name="filename">Filename.</param>
/// <returns><c>true</c>, if the update was successful, false otherwise.</returns>
private bool UpdateFileLastAccessTime(string filename)
{
try
{
File.SetLastAccessTime(filename, DateTime.Now);
return true;
}
catch
{
return false;
}
}
private AssetBase GetFromWeakReference(string id)
{
AssetBase asset = null;
WeakReference aref;
lock(weakAssetReferencesLock)
{
if (weakAssetReferences.TryGetValue(id, out aref))
{
asset = aref.Target as AssetBase;
if(asset == null)
weakAssetReferences.Remove(id);
else
m_weakRefHits++;
}
}
return asset;
}
/// <summary>
/// Try to get an asset from the in-memory cache.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private AssetBase GetFromMemoryCache(string id)
{
AssetBase asset = null;
if (m_MemoryCache.TryGetValue(id, out asset))
m_MemoryHits++;
return asset;
}
private bool CheckFromMemoryCache(string id)
{
return m_MemoryCache.Contains(id);
}
/// <summary>
/// Try to get an asset from the file cache.
/// </summary>
/// <param name="id"></param>
/// <returns>An asset retrieved from the file cache. null if there was a problem retrieving an asset.</returns>
private AssetBase GetFromFileCache(string id)
{
string filename = GetFileName(id);
#if WAIT_ON_INPROGRESS_REQUESTS
// Check if we're already downloading this asset. If so, try to wait for it to
// download.
if (m_WaitOnInprogressTimeout > 0)
{
m_RequestsForInprogress++;
ManualResetEvent waitEvent;
if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
{
waitEvent.WaitOne(m_WaitOnInprogressTimeout);
return Get(id);
}
}
#else
// Track how often we have the problem that an asset is requested while
// it is still being downloaded by a previous request.
if (m_CurrentlyWriting.Contains(filename))
{
m_RequestsForInprogress++;
return null;
}
#endif
AssetBase asset = null;
if (File.Exists(filename))
{
try
{
using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
if (stream.Length == 0) // Empty file will trigger exception below
return null;
BinaryFormatter bformatter = new BinaryFormatter();
asset = (AssetBase)bformatter.Deserialize(stream);
m_DiskHits++;
}
}
catch (System.Runtime.Serialization.SerializationException e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
filename, id, e.Message, e.StackTrace);
// If there was a problem deserializing the asset, the asset may
// either be corrupted OR was serialized under an old format
// {different version of AssetBase} -- we should attempt to
// delete it and re-cache
File.Delete(filename);
}
catch (Exception e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
filename, id, e.Message, e.StackTrace);
}
}
return asset;
}
private bool CheckFromFileCache(string id)
{
bool found = false;
string filename = GetFileName(id);
if (File.Exists(filename))
{
try
{
using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
if (stream != null)
found = true;
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[FLOTSAM ASSET CACHE]: Failed to check file {0} for asset {1}. Exception {2} {3}",
filename, id, e.Message, e.StackTrace);
}
}
return found;
}
// For IAssetService
public AssetBase Get(string id)
{
AssetBase asset;
Get(id, out asset);
return asset;
}
public bool Get(string id, out AssetBase asset)
{
asset = null;
m_Requests++;
object dummy;
if (m_negativeCache.TryGetValue(id, out dummy))
{
return false;
}
asset = GetFromWeakReference(id);
if (asset != null && m_updateFileTimeOnCacheHit)
{
string filename = GetFileName(id);
UpdateFileLastAccessTime(filename);
}
if (m_MemoryCacheEnabled && asset == null)
{
asset = GetFromMemoryCache(id);
if(asset != null)
{
UpdateWeakReference(id,asset);
if (m_updateFileTimeOnCacheHit)
{
string filename = GetFileName(id);
UpdateFileLastAccessTime(filename);
}
}
}
if (asset == null && m_FileCacheEnabled)
{
asset = GetFromFileCache(id);
if(asset != null)
UpdateWeakReference(id,asset);
}
if (m_MemoryCacheEnabled && asset != null)
UpdateMemoryCache(id, asset);
if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
{
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
GenerateCacheHitReport().ForEach(l => m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0}", l));
}
return true;
}
public bool Check(string id)
{
if (m_MemoryCacheEnabled && CheckFromMemoryCache(id))
return true;
if (m_FileCacheEnabled && CheckFromFileCache(id))
return true;
return false;
}
public AssetBase GetCached(string id)
{
AssetBase asset;
Get(id, out asset);
return asset;
}
public void Expire(string id)
{
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
try
{
if (m_FileCacheEnabled)
{
string filename = GetFileName(id);
if (File.Exists(filename))
{
File.Delete(filename);
}
}
if (m_MemoryCacheEnabled)
m_MemoryCache.Remove(id);
lock(weakAssetReferencesLock)
weakAssetReferences.Remove(id);
}
catch (Exception e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
id, e.Message, e.StackTrace);
}
}
public void Clear()
{
if (m_LogLevel >= 2)
m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
if (m_FileCacheEnabled && Directory.Exists(m_CacheDirectory))
{
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
Directory.Delete(dir);
}
}
if (m_MemoryCacheEnabled)
m_MemoryCache = new ExpiringCache<string, AssetBase>();
if (m_negativeCacheEnabled)
m_negativeCache = new ExpiringCache<string, object>();
lock(weakAssetReferencesLock)
weakAssetReferences = new Dictionary<string, WeakReference>();
}
private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
{
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration);
lock(timerLock)
{
if(!m_timerRunning || m_cleanupRunning)
return;
m_cleanupRunning = true;
}
// Purge all files last accessed prior to this point
DateTime purgeLine = DateTime.Now - m_FileExpiration;
// An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
// before cleaning up expired files we must scan the objects in the scene to make sure that we retain
// such local assets if they have not been recently accessed.
TouchAllSceneAssets(false);
if(Directory.Exists(m_CacheDirectory))
{
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
CleanExpiredFiles(dir, purgeLine);
}
lock(timerLock)
{
if(m_timerRunning)
m_CacheCleanTimer.Start();
m_cleanupRunning = false;
}
}
/// <summary>
/// Recurses through specified directory checking for asset files last
/// accessed prior to the specified purge line and deletes them. Also
/// removes empty tier directories.
/// </summary>
/// <param name="dir"></param>
/// <param name="purgeLine"></param>
private void CleanExpiredFiles(string dir, DateTime purgeLine)
{
try
{
if(!Directory.Exists(dir))
return;
foreach (string file in Directory.GetFiles(dir))
{
if (File.GetLastAccessTime(file) < purgeLine)
{
File.Delete(file);
}
}
// Recurse into lower tiers
foreach (string subdir in Directory.GetDirectories(dir))
{
CleanExpiredFiles(subdir, purgeLine);
}
// Check if a tier directory is empty, if so, delete it
int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
if (dirSize == 0)
{
Directory.Delete(dir);
}
else if (dirSize >= m_CacheWarnAt)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration",
dir, dirSize);
}
}
catch (DirectoryNotFoundException)
{
// If we get here, another node on the same box has
// already removed the directory. Continue with next.
}
catch (Exception e)
{
m_log.Warn(
string.Format("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception ", dir), e);
}
}
/// <summary>
/// Determines the filename for an AssetID stored in the file cache
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private string GetFileName(string id)
{
// Would it be faster to just hash the darn thing?
foreach (char c in m_InvalidChars)
{
id = id.Replace(c, '_');
}
string path = m_CacheDirectory;
for (int p = 1; p <= m_CacheDirectoryTiers; p++)
{
string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
path = Path.Combine(path, pathPart);
}
return Path.Combine(path, id);
}
/// <summary>
/// Writes a file to the file cache, creating any nessesary
/// tier directories along the way
/// </summary>
/// <param name="filename"></param>
/// <param name="asset"></param>
private void WriteFileCache(string filename, AssetBase asset)
{
Stream stream = null;
// Make sure the target cache directory exists
string directory = Path.GetDirectoryName(filename);
// Write file first to a temp name, so that it doesn't look
// like it's already cached while it's still writing.
string tempname = Path.Combine(directory, Path.GetRandomFileName());
try
{
try
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
stream = File.Open(tempname, FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, asset);
}
catch (IOException e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
return;
}
catch (UnauthorizedAccessException)
{
}
finally
{
if (stream != null)
stream.Close();
}
try
{
// Now that it's written, rename it so that it can be found.
//
// File.Copy(tempname, filename, true);
// File.Delete(tempname);
//
// For a brief period, this was done as a separate copy and then temporary file delete operation to
// avoid an IOException caused by move if some competing thread had already written the file.
// However, this causes exceptions on Windows when other threads attempt to read a file
// which is still being copied. So instead, go back to moving the file and swallow any IOException.
//
// This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the
// filesystem.
File.Move(tempname, filename);
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
}
catch (IOException)
{
// If we see an IOException here it's likely that some other competing thread has written the
// cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
// signally by the earlier temporary file writing code.
}
}
finally
{
// Even if the write fails with an exception, we need to make sure
// that we release the lock on that file, otherwise it'll never get
// cached
lock (m_CurrentlyWriting)
{
#if WAIT_ON_INPROGRESS_REQUESTS
ManualResetEvent waitEvent;
if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
{
m_CurrentlyWriting.Remove(filename);
waitEvent.Set();
}
#else
m_CurrentlyWriting.Remove(filename);
#endif
}
}
}
/// <summary>
/// Scan through the file cache, and return number of assets currently cached.
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
private int GetFileCacheCount(string dir)
{
if(!Directory.Exists(dir))
return 0;
int count = Directory.GetFiles(dir).Length;
foreach (string subdir in Directory.GetDirectories(dir))
{
count += GetFileCacheCount(subdir);
}
return count;
}
/// <summary>
/// This notes the last time the Region had a deep asset scan performed on it.
/// </summary>
/// <param name="regionID"></param>
private void StampRegionStatusFile(UUID regionID)
{
string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + regionID.ToString() + ".fac");
try
{
if (File.Exists(RegionCacheStatusFile))
{
File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
}
else
{
File.WriteAllText(
RegionCacheStatusFile,
"Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
}
}
catch (Exception e)
{
m_log.Warn(
string.Format(
"[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception ",
regionID),
e);
}
}
/// <summary>
/// Iterates through all Scenes, doing a deep scan through assets
/// to update the access time of all assets present in the scene or referenced by assets
/// in the scene.
/// </summary>
/// <param name="storeUncached">
/// If true, then assets scanned which are not found in cache are added to the cache.
/// </param>
/// <returns>Number of distinct asset references found in the scene.</returns>
private int TouchAllSceneAssets(bool storeUncached)
{
UuidGatherer gatherer = new UuidGatherer(m_AssetService);
Dictionary<UUID, bool> assetsFound = new Dictionary<UUID, bool>();
foreach (Scene s in m_Scenes)
{
StampRegionStatusFile(s.RegionInfo.RegionID);
s.ForEachSOG(delegate(SceneObjectGroup e)
{
if(!m_timerRunning && !storeUncached)
return;
gatherer.AddForInspection(e);
gatherer.GatherAll();
if(!m_timerRunning && !storeUncached)
return;
foreach (UUID assetID in gatherer.GatheredUuids.Keys)
{
if (!assetsFound.ContainsKey(assetID))
{
string filename = GetFileName(assetID.ToString());
if (File.Exists(filename))
{
UpdateFileLastAccessTime(filename);
assetsFound[assetID] = true;
}
else if (storeUncached)
{
AssetBase cachedAsset = m_AssetService.Get(assetID.ToString());
if (cachedAsset == null && gatherer.GatheredUuids[assetID] != (sbyte)AssetType.Unknown)
assetsFound[assetID] = false;
else
assetsFound[assetID] = true;
}
}
else if (!assetsFound[assetID])
{
m_log.DebugFormat(
"[FLOTSAM ASSET CACHE]: Could not find asset {0}, type {1} referenced by object {2} at {3} in scene {4} when pre-caching all scene assets",
assetID, gatherer.GatheredUuids[assetID], e.Name, e.AbsolutePosition, s.Name);
}
}
gatherer.GatheredUuids.Clear();
if(!m_timerRunning && !storeUncached)
return;
if(!storeUncached)
Thread.Sleep(50);
});
if(!m_timerRunning && !storeUncached)
break;
}
return assetsFound.Count;
}
/// <summary>
/// Deletes all cache contents
/// </summary>
private void ClearFileCache()
{
if(!Directory.Exists(m_CacheDirectory))
return;
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
try
{
Directory.Delete(dir, true);
}
catch (Exception e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
dir, m_CacheDirectory, e.Message, e.StackTrace);
}
}
foreach (string file in Directory.GetFiles(m_CacheDirectory))
{
try
{
File.Delete(file);
}
catch (Exception e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
file, m_CacheDirectory, e.Message, e.StackTrace);
}
}
}
private List<string> GenerateCacheHitReport()
{
List<string> outputLines = new List<string>();
double invReq = 100.0 / m_Requests;
double weakHitRate = m_weakRefHits * invReq;
int weakEntries = weakAssetReferences.Count;
double fileHitRate = m_DiskHits * invReq;
double TotalHitRate = weakHitRate + fileHitRate;
outputLines.Add(
string.Format("Total requests: {0}", m_Requests));
outputLines.Add(
string.Format("unCollected Hit Rate: {0}% ({1} entries)", weakHitRate.ToString("0.00"),weakEntries));
outputLines.Add(
string.Format("File Hit Rate: {0}%", fileHitRate.ToString("0.00")));
if (m_MemoryCacheEnabled)
{
double HitRate = m_MemoryHits * invReq;
outputLines.Add(
string.Format("Memory Hit Rate: {0}%", HitRate.ToString("0.00")));
TotalHitRate += HitRate;
}
outputLines.Add(
string.Format("Total Hit Rate: {0}%", TotalHitRate.ToString("0.00")));
outputLines.Add(
string.Format(
"Requests overlap during file writing: {0}", m_RequestsForInprogress));
return outputLines;
}
#region Console Commands
private void HandleConsoleCommand(string module, string[] cmdparams)
{
ICommandConsole con = MainConsole.Instance;
if (cmdparams.Length >= 2)
{
string cmd = cmdparams[1];
switch (cmd)
{
case "status":
if (m_MemoryCacheEnabled)
con.OutputFormat("Memory Cache: {0} assets", m_MemoryCache.Count);
else
con.OutputFormat("Memory cache disabled");
if (m_FileCacheEnabled)
{
int fileCount = GetFileCacheCount(m_CacheDirectory);
con.OutputFormat("File Cache: {0} assets", fileCount);
}
else
{
con.Output("File cache disabled");
}
GenerateCacheHitReport().ForEach(l => con.Output(l));
if (m_FileCacheEnabled)
{
con.Output("Deep scans have previously been performed on the following regions:");
foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
{
string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
con.OutputFormat("Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
}
}
break;
case "clear":
if (cmdparams.Length < 2)
{
con.Output("Usage is fcache clear [file] [memory]");
break;
}
bool clearMemory = false, clearFile = false;
if (cmdparams.Length == 2)
{
clearMemory = true;
clearFile = true;
}
foreach (string s in cmdparams)
{
if (s.ToLower() == "memory")
clearMemory = true;
else if (s.ToLower() == "file")
clearFile = true;
}
if (clearMemory)
{
if (m_MemoryCacheEnabled)
{
m_MemoryCache.Clear();
con.Output("Memory cache cleared.");
}
else
{
con.Output("Memory cache not enabled.");
}
}
if (clearFile)
{
if (m_FileCacheEnabled)
{
ClearFileCache();
con.Output("File cache cleared.");
}
else
{
con.Output("File cache not enabled.");
}
}
break;
case "assets":
lock(timerLock)
{
if(m_cleanupRunning)
{
con.OutputFormat("Flotsam assets check already running");
return;
}
m_cleanupRunning = true;
}
con.Output("Flotsam Ensuring assets are cached for all scenes.");
WorkManager.RunInThreadPool(delegate
{
bool wasRunning= false;
lock(timerLock)
{
if(m_timerRunning)
{
m_CacheCleanTimer.Stop();
m_timerRunning = false;
wasRunning = true;
Thread.Sleep(100);
}
}
int assetReferenceTotal = TouchAllSceneAssets(true);
GC.Collect();
lock(timerLock)
{
if(wasRunning)
{
m_CacheCleanTimer.Start();
m_timerRunning = true;
}
m_cleanupRunning = false;
}
con.OutputFormat("Completed check with {0} assets.", assetReferenceTotal);
}, null, "TouchAllSceneAssets", false);
break;
case "expire":
if (cmdparams.Length < 3)
{
con.OutputFormat("Invalid parameters for Expire, please specify a valid date & time", cmd);
break;
}
string s_expirationDate = "";
DateTime expirationDate;
if (cmdparams.Length > 3)
{
s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
}
else
{
s_expirationDate = cmdparams[2];
}
if (!DateTime.TryParse(s_expirationDate, out expirationDate))
{
con.OutputFormat("{0} is not a valid date & time", cmd);
break;
}
if (m_FileCacheEnabled)
CleanExpiredFiles(m_CacheDirectory, expirationDate);
else
con.OutputFormat("File cache not active, not clearing.");
break;
default:
con.OutputFormat("Unknown command {0}", cmd);
break;
}
}
else if (cmdparams.Length == 1)
{
con.Output("fcache assets - Attempt a deep cache of all assets in all scenes");
con.Output("fcache expire <datetime> - Purge assets older then the specified date & time");
con.Output("fcache clear [file] [memory] - Remove cached assets");
con.Output("fcache status - Display cache status");
}
}
#endregion
#region IAssetService Members
public AssetMetadata GetMetadata(string id)
{
AssetBase asset;
Get(id, out asset);
return asset.Metadata;
}
public byte[] GetData(string id)
{
AssetBase asset;
Get(id, out asset);
return asset.Data;
}
public bool Get(string id, object sender, AssetRetrieved handler)
{
AssetBase asset;
if (!Get(id, out asset))
return false;
handler(id, sender, asset);
return true;
}
public bool[] AssetsExist(string[] ids)
{
bool[] exist = new bool[ids.Length];
for (int i = 0; i < ids.Length; i++)
{
exist[i] = Check(ids[i]);
}
return exist;
}
public string Store(AssetBase asset)
{
if (asset.FullID == UUID.Zero)
{
asset.FullID = UUID.Random();
}
Cache(asset);
return asset.ID;
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset;
if (!Get(id, out asset))
return false;
asset.Data = data;
Cache(asset);
return true;
}
public bool Delete(string id)
{
Expire(id);
return true;
}
#endregion
}
}
| |
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Embedding;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Input.TextInput;
using Avalonia.Web.Blazor.Interop;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
using SkiaSharp;
namespace Avalonia.Web.Blazor
{
public partial class AvaloniaView : ITextInputMethodImpl
{
private readonly RazorViewTopLevelImpl _topLevelImpl;
private EmbeddableControlRoot _topLevel;
// Interop
private SKHtmlCanvasInterop _interop = null!;
private SizeWatcherInterop _sizeWatcher = null!;
private DpiWatcherInterop _dpiWatcher = null!;
private SKHtmlCanvasInterop.GLInfo? _jsGlInfo = null!;
private InputHelperInterop _inputHelper = null!;
private ElementReference _htmlCanvas;
private ElementReference _inputElement;
private double _dpi;
private SKSize _canvasSize;
private GRContext? _context;
private GRGlInterface? _glInterface;
private const SKColorType ColorType = SKColorType.Rgba8888;
private bool _initialised;
[Inject] private IJSRuntime Js { get; set; } = null!;
public AvaloniaView()
{
_topLevelImpl = new RazorViewTopLevelImpl(this);
_topLevel = new EmbeddableControlRoot(_topLevelImpl);
if (Application.Current?.ApplicationLifetime is ISingleViewApplicationLifetime lifetime)
{
_topLevel.Content = lifetime.MainView;
}
}
private void OnTouchStart(TouchEventArgs e)
{
foreach (var touch in e.ChangedTouches)
{
_topLevelImpl.RawTouchEvent(RawPointerEventType.TouchBegin, new Point(touch.ClientX, touch.ClientY),
GetModifiers(e), touch.Identifier);
}
}
private void OnTouchEnd(TouchEventArgs e)
{
foreach (var touch in e.ChangedTouches)
{
_topLevelImpl.RawTouchEvent(RawPointerEventType.TouchEnd, new Point(touch.ClientX, touch.ClientY),
GetModifiers(e), touch.Identifier);
}
}
private void OnTouchCancel(TouchEventArgs e)
{
foreach (var touch in e.ChangedTouches)
{
_topLevelImpl.RawTouchEvent(RawPointerEventType.TouchCancel, new Point(touch.ClientX, touch.ClientY),
GetModifiers(e), touch.Identifier);
}
}
private void OnTouchMove(TouchEventArgs e)
{
foreach (var touch in e.ChangedTouches)
{
_topLevelImpl.RawTouchEvent(RawPointerEventType.TouchUpdate, new Point(touch.ClientX, touch.ClientY),
GetModifiers(e), touch.Identifier);
}
}
private void OnMouseMove(MouseEventArgs e)
{
_topLevelImpl.RawMouseEvent(RawPointerEventType.Move, new Point(e.ClientX, e.ClientY), GetModifiers(e));
}
private void OnMouseUp(MouseEventArgs e)
{
RawPointerEventType type = default;
switch (e.Button)
{
case 0:
type = RawPointerEventType.LeftButtonUp;
break;
case 1:
type = RawPointerEventType.MiddleButtonUp;
break;
case 2:
type = RawPointerEventType.RightButtonUp;
break;
}
_topLevelImpl.RawMouseEvent(type, new Point(e.ClientX, e.ClientY), GetModifiers(e));
}
private void OnMouseDown(MouseEventArgs e)
{
RawPointerEventType type = default;
switch (e.Button)
{
case 0:
type = RawPointerEventType.LeftButtonDown;
break;
case 1:
type = RawPointerEventType.MiddleButtonDown;
break;
case 2:
type = RawPointerEventType.RightButtonDown;
break;
}
_topLevelImpl.RawMouseEvent(type, new Point(e.ClientX, e.ClientY), GetModifiers(e));
}
private void OnWheel(WheelEventArgs e)
{
_topLevelImpl.RawMouseWheelEvent(new Point(e.ClientX, e.ClientY),
new Vector(-(e.DeltaX / 50), -(e.DeltaY / 50)), GetModifiers(e));
}
private static RawInputModifiers GetModifiers(WheelEventArgs e)
{
var modifiers = RawInputModifiers.None;
if (e.CtrlKey)
modifiers |= RawInputModifiers.Control;
if (e.AltKey)
modifiers |= RawInputModifiers.Alt;
if (e.ShiftKey)
modifiers |= RawInputModifiers.Shift;
if (e.MetaKey)
modifiers |= RawInputModifiers.Meta;
if ((e.Buttons & 1L) == 1)
modifiers |= RawInputModifiers.LeftMouseButton;
if ((e.Buttons & 2L) == 2)
modifiers |= RawInputModifiers.RightMouseButton;
if ((e.Buttons & 4L) == 4)
modifiers |= RawInputModifiers.MiddleMouseButton;
return modifiers;
}
private static RawInputModifiers GetModifiers(TouchEventArgs e)
{
var modifiers = RawInputModifiers.None;
if (e.CtrlKey)
modifiers |= RawInputModifiers.Control;
if (e.AltKey)
modifiers |= RawInputModifiers.Alt;
if (e.ShiftKey)
modifiers |= RawInputModifiers.Shift;
if (e.MetaKey)
modifiers |= RawInputModifiers.Meta;
return modifiers;
}
private static RawInputModifiers GetModifiers(MouseEventArgs e)
{
var modifiers = RawInputModifiers.None;
if (e.CtrlKey)
modifiers |= RawInputModifiers.Control;
if (e.AltKey)
modifiers |= RawInputModifiers.Alt;
if (e.ShiftKey)
modifiers |= RawInputModifiers.Shift;
if (e.MetaKey)
modifiers |= RawInputModifiers.Meta;
if ((e.Buttons & 1L) == 1)
modifiers |= RawInputModifiers.LeftMouseButton;
if ((e.Buttons & 2L) == 2)
modifiers |= RawInputModifiers.RightMouseButton;
if ((e.Buttons & 4L) == 4)
modifiers |= RawInputModifiers.MiddleMouseButton;
return modifiers;
}
private static RawInputModifiers GetModifiers(KeyboardEventArgs e)
{
var modifiers = RawInputModifiers.None;
if (e.CtrlKey)
modifiers |= RawInputModifiers.Control;
if (e.AltKey)
modifiers |= RawInputModifiers.Alt;
if (e.ShiftKey)
modifiers |= RawInputModifiers.Shift;
if (e.MetaKey)
modifiers |= RawInputModifiers.Meta;
return modifiers;
}
private void OnKeyDown(KeyboardEventArgs e)
{
_topLevelImpl.RawKeyboardEvent(RawKeyEventType.KeyDown, e.Key, GetModifiers(e));
}
private void OnKeyUp(KeyboardEventArgs e)
{
_topLevelImpl.RawKeyboardEvent(RawKeyEventType.KeyUp, e.Code, GetModifiers(e));
}
private void OnInput(ChangeEventArgs e)
{
if (e.Value != null)
{
var inputData = e.Value.ToString();
if (inputData != null)
{
_topLevelImpl.RawTextEvent(inputData);
}
}
_inputHelper.Clear();
}
[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
Threading.Dispatcher.UIThread.Post(async () =>
{
_inputHelper = await InputHelperInterop.ImportAsync(Js, _inputElement);
_inputHelper.Hide();
_inputHelper.SetCursor("default");
Console.WriteLine("starting html canvas setup");
_interop = await SKHtmlCanvasInterop.ImportAsync(Js, _htmlCanvas, OnRenderFrame);
Console.WriteLine("Interop created");
_jsGlInfo = _interop.InitGL();
Console.WriteLine("jsglinfo created - init gl");
_sizeWatcher = await SizeWatcherInterop.ImportAsync(Js, _htmlCanvas, OnSizeChanged);
_dpiWatcher = await DpiWatcherInterop.ImportAsync(Js, OnDpiChanged);
Console.WriteLine("watchers created.");
// create the SkiaSharp context
if (_context == null)
{
Console.WriteLine("create glcontext");
_glInterface = GRGlInterface.Create();
_context = GRContext.CreateGl(_glInterface);
var options = AvaloniaLocator.Current.GetService<SkiaOptions>();
// bump the default resource cache limit
_context.SetResourceCacheLimit(options?.MaxGpuResourceSizeBytes ?? 32 * 1024 * 1024);
Console.WriteLine("glcontext created and resource limit set");
}
_topLevelImpl.SetSurface(_context, _jsGlInfo, ColorType,
new PixelSize((int)_canvasSize.Width, (int)_canvasSize.Height), _dpi);
_initialised = true;
_topLevel.Prepare();
_topLevel.Renderer.Start();
Invalidate();
});
}
}
private void OnRenderFrame()
{
if (_canvasSize.Width <= 0 || _canvasSize.Height <= 0 || _dpi <= 0 || _jsGlInfo == null)
{
Console.WriteLine("nothing to render");
return;
}
ManualTriggerRenderTimer.Instance.RaiseTick();
}
public void Dispose()
{
_dpiWatcher.Unsubscribe(OnDpiChanged);
_sizeWatcher.Dispose();
_interop.Dispose();
}
private void OnDpiChanged(double newDpi)
{
_dpi = newDpi;
_topLevelImpl.SetClientSize(_canvasSize, _dpi);
Invalidate();
}
private void OnSizeChanged(SKSize newSize)
{
_canvasSize = newSize;
_topLevelImpl.SetClientSize(_canvasSize, _dpi);
Invalidate();
}
public void Invalidate()
{
if (!_initialised || _canvasSize.Width <= 0 || _canvasSize.Height <= 0 || _dpi <= 0 || _jsGlInfo == null)
{
Console.WriteLine("invalidate ignored");
return;
}
_interop.RequestAnimationFrame(true, (int)(_canvasSize.Width * _dpi), (int)(_canvasSize.Height * _dpi));
}
public void SetActive(bool active)
{
_inputHelper.Clear();
if (active)
{
_inputHelper.Show();
_inputHelper.Focus();
}
else
{
_inputHelper.Hide();
}
}
public void SetCursorRect(Rect rect)
{
}
public void SetOptions(TextInputOptionsQueryEventArgs options)
{
}
public void Reset()
{
_inputHelper.Clear();
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using QuantConnect.AlgorithmFactory;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Logging;
using QuantConnect.Packets;
using QuantConnect.Util;
using HistoryRequest = QuantConnect.Data.HistoryRequest;
namespace QuantConnect.Lean.Engine.Setup
{
/// <summary>
/// Base class that provides shared code for
/// the <see cref="ISetupHandler"/> implementations
/// </summary>
public static class BaseSetupHandler
{
/// <summary>
/// Get the maximum time that the creation of an algorithm can take
/// </summary>
public static TimeSpan AlgorithmCreationTimeout { get; } = TimeSpan.FromSeconds(Config.GetDouble("algorithm-creation-timeout", 90));
/// <summary>
/// Will first check and add all the required conversion rate securities
/// and later will seed an initial value to them.
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="universeSelection">The universe selection instance</param>
public static void SetupCurrencyConversions(
IAlgorithm algorithm,
UniverseSelection universeSelection)
{
// this is needed to have non-zero currency conversion rates during warmup
// will also set the Cash.ConversionRateSecurity
universeSelection.EnsureCurrencyDataFeeds(SecurityChanges.None);
// now set conversion rates
var cashToUpdate = algorithm.Portfolio.CashBook.Values
.Where(x => x.CurrencyConversion != null && x.ConversionRate == 0)
.ToList();
var securitiesToUpdate = cashToUpdate
.SelectMany(x => x.CurrencyConversion.ConversionRateSecurities)
.Distinct()
.ToList();
var historyRequestFactory = new HistoryRequestFactory(algorithm);
var historyRequests = new List<HistoryRequest>();
foreach (var security in securitiesToUpdate)
{
var configs = algorithm
.SubscriptionManager
.SubscriptionDataConfigService
.GetSubscriptionDataConfigs(security.Symbol,
includeInternalConfigs: true);
// we need to order and select a specific configuration type
// so the conversion rate is deterministic
var configToUse = configs.OrderBy(x => x.TickType).First();
var hours = security.Exchange.Hours;
var resolution = configs.GetHighestResolution();
var startTime = historyRequestFactory.GetStartTimeAlgoTz(
security.Symbol,
60,
resolution,
hours,
configToUse.DataTimeZone);
var endTime = algorithm.Time;
historyRequests.Add(historyRequestFactory.CreateHistoryRequest(
configToUse,
startTime,
endTime,
security.Exchange.Hours,
resolution));
}
// Attempt to get history for these requests and update cash
var slices = algorithm.HistoryProvider.GetHistory(historyRequests, algorithm.TimeZone);
slices.PushThrough(data =>
{
foreach (var security in securitiesToUpdate.Where(x => x.Symbol == data.Symbol))
{
security.SetMarketPrice(data);
}
});
foreach (var cash in cashToUpdate)
{
cash.Update();
}
// Any remaining unassigned cash will attempt to fall back to a daily resolution history request to resolve
var unassignedCash = cashToUpdate.Where(x => x.ConversionRate == 0).ToList();
if (unassignedCash.Any())
{
Log.Trace(
$"Failed to assign conversion rates for the following cash: {string.Join(",", unassignedCash.Select(x => x.Symbol))}." +
$" Attempting to request daily resolution history to resolve conversion rate");
var unassignedCashSymbols = unassignedCash
.SelectMany(x => x.SecuritySymbols)
.ToHashSet();
var replacementHistoryRequests = new List<HistoryRequest>();
foreach (var request in historyRequests.Where(x =>
unassignedCashSymbols.Contains(x.Symbol) && x.Resolution < Resolution.Daily))
{
var newRequest = new HistoryRequest(request.EndTimeUtc.AddDays(-10), request.EndTimeUtc,
request.DataType,
request.Symbol, Resolution.Daily, request.ExchangeHours, request.DataTimeZone,
request.FillForwardResolution,
request.IncludeExtendedMarketHours, request.IsCustomData, request.DataNormalizationMode,
request.TickType);
replacementHistoryRequests.Add(newRequest);
}
slices = algorithm.HistoryProvider.GetHistory(replacementHistoryRequests, algorithm.TimeZone);
slices.PushThrough(data =>
{
foreach (var security in securitiesToUpdate.Where(x => x.Symbol == data.Symbol))
{
security.SetMarketPrice(data);
}
});
foreach (var cash in unassignedCash)
{
cash.Update();
}
}
Log.Trace("BaseSetupHandler.SetupCurrencyConversions():" +
$"{Environment.NewLine}{algorithm.Portfolio.CashBook}");
}
/// <summary>
/// Initialize the debugger
/// </summary>
/// <param name="algorithmNodePacket">The algorithm node packet</param>
/// <param name="workerThread">The worker thread instance to use</param>
public static bool InitializeDebugging(AlgorithmNodePacket algorithmNodePacket, WorkerThread workerThread)
{
var isolator = new Isolator();
return isolator.ExecuteWithTimeLimit(TimeSpan.FromMinutes(5),
() => DebuggerHelper.Initialize(algorithmNodePacket.Language),
algorithmNodePacket.RamAllocation,
sleepIntervalMillis: 100,
workerThread: workerThread);
}
/// <summary>
/// Sets the initial cash for the algorithm if set in the job packet.
/// </summary>
/// <remarks>Should be called after initialize <see cref="LoadBacktestJobAccountCurrency"/></remarks>
public static void LoadBacktestJobCashAmount(IAlgorithm algorithm, BacktestNodePacket job)
{
// set initial cash, if present in the job
if (job.CashAmount.HasValue)
{
// Zero the CashBook - we'll populate directly from job
foreach (var kvp in algorithm.Portfolio.CashBook)
{
kvp.Value.SetAmount(0);
}
algorithm.SetCash(job.CashAmount.Value.Amount);
}
}
/// <summary>
/// Sets the account currency the algorithm should use if set in the job packet
/// </summary>
/// <remarks>Should be called before initialize <see cref="LoadBacktestJobCashAmount"/></remarks>
public static void LoadBacktestJobAccountCurrency(IAlgorithm algorithm, BacktestNodePacket job)
{
// set account currency if present in the job
if (job.CashAmount.HasValue)
{
algorithm.SetAccountCurrency(job.CashAmount.Value.Currency);
}
}
/// <summary>
/// Get the available data feeds from config.json,
/// </summary>
public static Dictionary<SecurityType, List<TickType>> GetConfiguredDataFeeds()
{
var dataFeedsConfigString = Config.Get("security-data-feeds");
if (!dataFeedsConfigString.IsNullOrEmpty())
{
var dataFeeds = JsonConvert.DeserializeObject<Dictionary<SecurityType, List<TickType>>>(dataFeedsConfigString);
return dataFeeds;
}
return null;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
using NLog.Common;
using NLog.Conditions;
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
/// <summary>
/// Reflection helpers for accessing properties.
/// </summary>
internal static class PropertyHelper
{
private static Dictionary<Type, Dictionary<string, PropertyInfo>> parameterInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>();
internal static void SetPropertyFromString(object o, string name, string value, ConfigurationItemFactory configurationItemFactory)
{
InternalLogger.Debug("Setting '{0}.{1}' to '{2}'", o.GetType().Name, name, value);
PropertyInfo propInfo;
if (!TryGetPropertyInfo(o, name, out propInfo))
{
throw new NotSupportedException("Parameter " + name + " not supported on " + o.GetType().Name);
}
try
{
if (propInfo.IsDefined(typeof(ArrayParameterAttribute), false))
{
throw new NotSupportedException("Parameter " + name + " of " + o.GetType().Name + " is an array and cannot be assigned a scalar value.");
}
object newValue;
Type propertyType = propInfo.PropertyType;
propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType;
if (!TryNLogSpecificConversion(propertyType, value, out newValue, configurationItemFactory))
{
if (!TryGetEnumValue(propertyType, value, out newValue))
{
if (!TryImplicitConversion(propertyType, value, out newValue))
{
if (!TrySpecialConversion(propertyType, value, out newValue))
{
newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
}
}
}
}
propInfo.SetValue(o, newValue, null);
}
catch (TargetInvocationException ex)
{
throw new NLogConfigurationException("Error when setting property '" + propInfo.Name + "' on " + o, ex.InnerException);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
throw new NLogConfigurationException("Error when setting property '" + propInfo.Name + "' on " + o, exception);
}
}
internal static bool IsArrayProperty(Type t, string name)
{
PropertyInfo propInfo;
if (!TryGetPropertyInfo(t, name, out propInfo))
{
throw new NotSupportedException("Parameter " + name + " not supported on " + t.Name);
}
return propInfo.IsDefined(typeof(ArrayParameterAttribute), false);
}
internal static bool TryGetPropertyInfo(object o, string propertyName, out PropertyInfo result)
{
PropertyInfo propInfo = o.GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propInfo != null)
{
result = propInfo;
return true;
}
lock (parameterInfoCache)
{
Type targetType = o.GetType();
Dictionary<string, PropertyInfo> cache;
if (!parameterInfoCache.TryGetValue(targetType, out cache))
{
cache = BuildPropertyInfoDictionary(targetType);
parameterInfoCache[targetType] = cache;
}
return cache.TryGetValue(propertyName, out result);
}
}
internal static Type GetArrayItemType(PropertyInfo propInfo)
{
var arrayParameterAttribute = (ArrayParameterAttribute)Attribute.GetCustomAttribute(propInfo, typeof(ArrayParameterAttribute));
if (arrayParameterAttribute != null)
{
return arrayParameterAttribute.ItemType;
}
return null;
}
internal static IEnumerable<PropertyInfo> GetAllReadableProperties(Type type)
{
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
internal static void CheckRequiredParameters(object o)
{
foreach (PropertyInfo propInfo in PropertyHelper.GetAllReadableProperties(o.GetType()))
{
if (propInfo.IsDefined(typeof(RequiredParameterAttribute), false))
{
object value = propInfo.GetValue(o, null);
if (value == null)
{
throw new NLogConfigurationException(
"Required parameter '" + propInfo.Name + "' on '" + o + "' was not specified.");
}
}
}
}
private static bool TryImplicitConversion(Type resultType, string value, out object result)
{
MethodInfo operatorImplicitMethod = resultType.GetMethod("op_Implicit", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
if (operatorImplicitMethod == null)
{
result = null;
return false;
}
result = operatorImplicitMethod.Invoke(null, new object[] { value });
return true;
}
private static bool TryNLogSpecificConversion(Type propertyType, string value, out object newValue, ConfigurationItemFactory configurationItemFactory)
{
if (propertyType == typeof(Layout) || propertyType == typeof(SimpleLayout))
{
newValue = new SimpleLayout(value, configurationItemFactory);
return true;
}
if (propertyType == typeof(ConditionExpression))
{
newValue = ConditionParser.ParseExpression(value, configurationItemFactory);
return true;
}
newValue = null;
return false;
}
private static bool TryGetEnumValue(Type resultType, string value, out object result)
{
if (!resultType.IsEnum)
{
result = null;
return false;
}
if (resultType.IsDefined(typeof(FlagsAttribute), false))
{
ulong union = 0;
foreach (string v in value.Split(','))
{
FieldInfo enumField = resultType.GetField(v.Trim(), BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public);
if (enumField == null)
{
throw new NLogConfigurationException("Invalid enumeration value '" + value + "'.");
}
union |= Convert.ToUInt64(enumField.GetValue(null), CultureInfo.InvariantCulture);
}
result = Convert.ChangeType(union, Enum.GetUnderlyingType(resultType), CultureInfo.InvariantCulture);
result = Enum.ToObject(resultType, result);
return true;
}
else
{
FieldInfo enumField = resultType.GetField(value, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public);
if (enumField == null)
{
throw new NLogConfigurationException("Invalid enumeration value '" + value + "'.");
}
result = enumField.GetValue(null);
return true;
}
}
private static bool TrySpecialConversion(Type type, string value, out object newValue)
{
if (type == typeof(Uri))
{
newValue = new Uri(value, UriKind.RelativeOrAbsolute);
return true;
}
if (type == typeof(Encoding))
{
newValue = Encoding.GetEncoding(value);
return true;
}
if (type == typeof(CultureInfo))
{
newValue = new CultureInfo(value);
return true;
}
if (type == typeof(Type))
{
newValue = Type.GetType(value, true);
return true;
}
newValue = null;
return false;
}
private static bool TryGetPropertyInfo(Type targetType, string propertyName, out PropertyInfo result)
{
if (!string.IsNullOrEmpty(propertyName))
{
PropertyInfo propInfo = targetType.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propInfo != null)
{
result = propInfo;
return true;
}
}
lock (parameterInfoCache)
{
Dictionary<string, PropertyInfo> cache;
if (!parameterInfoCache.TryGetValue(targetType, out cache))
{
cache = BuildPropertyInfoDictionary(targetType);
parameterInfoCache[targetType] = cache;
}
return cache.TryGetValue(propertyName, out result);
}
}
private static Dictionary<string, PropertyInfo> BuildPropertyInfoDictionary(Type t)
{
var retVal = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
foreach (PropertyInfo propInfo in GetAllReadableProperties(t))
{
var arrayParameterAttribute = (ArrayParameterAttribute)Attribute.GetCustomAttribute(propInfo, typeof(ArrayParameterAttribute));
if (arrayParameterAttribute != null)
{
retVal[arrayParameterAttribute.ElementName] = propInfo;
}
else
{
retVal[propInfo.Name] = propInfo;
}
if (propInfo.IsDefined(typeof(DefaultParameterAttribute), false))
{
// define a property with empty name
retVal[string.Empty] = propInfo;
}
}
return retVal;
}
}
}
| |
// 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.Text.Encoding.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.Text
{
abstract public partial class Encoding : ICloneable
{
#region Methods and constructors
public virtual new Object Clone()
{
return default(Object);
}
public static byte[] Convert(System.Text.Encoding srcEncoding, System.Text.Encoding dstEncoding, byte[] bytes)
{
return default(byte[]);
}
public static byte[] Convert(System.Text.Encoding srcEncoding, System.Text.Encoding dstEncoding, byte[] bytes, int index, int count)
{
return default(byte[]);
}
protected Encoding()
{
}
protected Encoding(int codePage)
{
}
public override bool Equals(Object value)
{
return default(bool);
}
unsafe public virtual new int GetByteCount(char* chars, int count)
{
return default(int);
}
public virtual new int GetByteCount(char[] chars)
{
return default(int);
}
public virtual new int GetByteCount(string s)
{
return default(int);
}
public abstract int GetByteCount(char[] chars, int index, int count);
unsafe public virtual new int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return default(int);
}
public virtual new int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return default(int);
}
public virtual new byte[] GetBytes(char[] chars, int index, int count)
{
return default(byte[]);
}
public virtual new byte[] GetBytes(char[] chars)
{
return default(byte[]);
}
public virtual new byte[] GetBytes(string s)
{
return default(byte[]);
}
public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex);
public abstract int GetCharCount(byte[] bytes, int index, int count);
unsafe public virtual new int GetCharCount(byte* bytes, int count)
{
return default(int);
}
public virtual new int GetCharCount(byte[] bytes)
{
return default(int);
}
unsafe public virtual new int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return default(int);
}
public virtual new char[] GetChars(byte[] bytes, int index, int count)
{
return default(char[]);
}
public virtual new char[] GetChars(byte[] bytes)
{
return default(char[]);
}
public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);
public virtual new Decoder GetDecoder()
{
return default(Decoder);
}
public virtual new Encoder GetEncoder()
{
return default(Encoder);
}
public static System.Text.Encoding GetEncoding(string name)
{
return default(System.Text.Encoding);
}
public static System.Text.Encoding GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback)
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
public static System.Text.Encoding GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback)
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
public static System.Text.Encoding GetEncoding(int codepage)
{
return default(System.Text.Encoding);
}
public static EncodingInfo[] GetEncodings()
{
return default(EncodingInfo[]);
}
public override int GetHashCode()
{
return default(int);
}
public abstract int GetMaxByteCount(int charCount);
public abstract int GetMaxCharCount(int byteCount);
public virtual new byte[] GetPreamble()
{
return default(byte[]);
}
public virtual new string GetString(byte[] bytes)
{
return default(string);
}
public virtual new string GetString(byte[] bytes, int index, int count)
{
return default(string);
}
public bool IsAlwaysNormalized()
{
return default(bool);
}
public virtual new bool IsAlwaysNormalized(NormalizationForm form)
{
return default(bool);
}
#endregion
#region Properties and indexers
public static System.Text.Encoding ASCII
{
get
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
}
public static System.Text.Encoding BigEndianUnicode
{
get
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
}
public virtual new string BodyName
{
get
{
return default(string);
}
}
public virtual new int CodePage
{
get
{
return default(int);
}
}
public DecoderFallback DecoderFallback
{
get
{
return default(DecoderFallback);
}
set
{
}
}
public static System.Text.Encoding Default
{
get
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
}
public EncoderFallback EncoderFallback
{
get
{
return default(EncoderFallback);
}
set
{
}
}
public virtual new string EncodingName
{
get
{
return default(string);
}
}
public virtual new string HeaderName
{
get
{
return default(string);
}
}
public virtual new bool IsBrowserDisplay
{
get
{
return default(bool);
}
}
public virtual new bool IsBrowserSave
{
get
{
return default(bool);
}
}
public virtual new bool IsMailNewsDisplay
{
get
{
return default(bool);
}
}
public virtual new bool IsMailNewsSave
{
get
{
return default(bool);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public virtual new bool IsSingleByte
{
get
{
return default(bool);
}
}
public static System.Text.Encoding Unicode
{
get
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
}
public static System.Text.Encoding UTF32
{
get
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
}
public static System.Text.Encoding UTF7
{
get
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
}
public static System.Text.Encoding UTF8
{
get
{
Contract.Ensures(Contract.Result<System.Text.Encoding>() != null);
return default(System.Text.Encoding);
}
}
public virtual new string WebName
{
get
{
return default(string);
}
}
public virtual new int WindowsCodePage
{
get
{
return default(int);
}
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PowerShell.Commands;
namespace System.Management.Automation
{
/// <summary>
/// Class to manage the caching of analysis data.
///
/// For performance, module command caching is flattened after discovery. Many modules have nested
/// modules that can only be resolved at runtime - for example,
/// script modules that declare: $env:PATH += "; $psScriptRoot". When
/// doing initial analysis, we include these in 'ExportedCommands'.
///
/// Changes to these type of modules will not be re-analyzed, unless the user re-imports the module,
/// or runs Get-Module -List.
///
/// </summary>
internal class AnalysisCache
{
private static AnalysisCacheData s_cacheData = AnalysisCacheData.Get();
// This dictionary shouldn't see much use, so low concurrency and capacity
private static ConcurrentDictionary<string, string> s_modulesBeingAnalyzed =
new ConcurrentDictionary<string, string>( /*concurrency*/1, /*capacity*/2, StringComparer.OrdinalIgnoreCase);
internal static char[] InvalidCommandNameCharacters = new[]
{
'#', ',', '(', ')', '{', '}', '[', ']', '&', '/', '\\', '$', '^', ';', ':',
'"', '\'', '<', '>', '|', '?', '@', '`', '*', '%', '+', '=', '~'
};
internal static ConcurrentDictionary<string, CommandTypes> GetExportedCommands(string modulePath, bool testOnly, ExecutionContext context)
{
bool etwEnabled = CommandDiscoveryEventSource.Log.IsEnabled();
if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStart(modulePath);
DateTime lastWriteTime;
ModuleCacheEntry moduleCacheEntry;
if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry))
{
if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStop(modulePath);
return moduleCacheEntry.Commands;
}
ConcurrentDictionary<string, CommandTypes> result = null;
if (!testOnly)
{
var extension = Path.GetExtension(modulePath);
if (extension.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeManifestModule(modulePath, context, lastWriteTime, etwEnabled);
}
else if (extension.Equals(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeScriptModule(modulePath, context, lastWriteTime);
}
else if (extension.Equals(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeCdxmlModule(modulePath, context, lastWriteTime);
}
else if (extension.Equals(StringLiterals.WorkflowFileExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeXamlModule(modulePath, context, lastWriteTime);
}
else if (extension.Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeDllModule(modulePath, context, lastWriteTime);
}
}
if (result != null)
{
s_cacheData.QueueSerialization();
ModuleIntrinsics.Tracer.WriteLine("Returning {0} exported commands.", result.Count);
}
else
{
ModuleIntrinsics.Tracer.WriteLine("Returning NULL for exported commands.");
}
if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStop(modulePath);
return result;
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeManifestModule(string modulePath, ExecutionContext context, DateTime lastWriteTime, bool etwEnabled)
{
ConcurrentDictionary<string, CommandTypes> result = null;
try
{
var moduleManifestProperties = PsUtils.GetModuleManifestProperties(modulePath, PsUtils.FastModuleManifestAnalysisPropertyNames);
if (moduleManifestProperties != null)
{
Version version;
if (ModuleUtils.IsModuleInVersionSubdirectory(modulePath, out version))
{
var versionInManifest = LanguagePrimitives.ConvertTo<Version>(moduleManifestProperties["ModuleVersion"]);
if (version != versionInManifest)
{
ModuleIntrinsics.Tracer.WriteLine("ModuleVersion in manifest does not match versioned module directory, skipping module: {0}", modulePath);
return null;
}
}
result = new ConcurrentDictionary<string, CommandTypes>(3, moduleManifestProperties.Count, StringComparer.OrdinalIgnoreCase);
var sawWildcard = false;
var hadCmdlets = AddPsd1EntryToResult(result, moduleManifestProperties["CmdletsToExport"], CommandTypes.Cmdlet, ref sawWildcard);
var hadFunctions = AddPsd1EntryToResult(result, moduleManifestProperties["FunctionsToExport"], CommandTypes.Function, ref sawWildcard);
var hadAliases = AddPsd1EntryToResult(result, moduleManifestProperties["AliasesToExport"], CommandTypes.Alias, ref sawWildcard);
var analysisSuceeded = hadCmdlets && hadFunctions && hadAliases;
if (!analysisSuceeded && !sawWildcard && (hadCmdlets || hadFunctions))
{
// If we're missing CmdletsToExport, that might still be OK, but only if we have a script module.
// Likewise, if we're missing FunctionsToExport, that might be OK, but only if we have a binary module.
analysisSuceeded = !CheckModulesTypesInManifestAgainstExportedCommands(moduleManifestProperties, hadCmdlets, hadFunctions, hadAliases);
}
if (analysisSuceeded)
{
var moduleCacheEntry = new ModuleCacheEntry
{
ModulePath = modulePath,
LastWriteTime = lastWriteTime,
Commands = result,
TypesAnalyzed = false,
Types = new ConcurrentDictionary<string, TypeAttributes>(1, 8, StringComparer.OrdinalIgnoreCase)
};
s_cacheData.Entries[modulePath] = moduleCacheEntry;
}
else
{
result = null;
}
}
}
catch (Exception e)
{
if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleManifestAnalysisException(modulePath, e.Message);
// Ignore the errors, proceed with the usual module analysis
ModuleIntrinsics.Tracer.WriteLine("Exception on fast-path analysis of module {0}", modulePath);
}
if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleManifestAnalysisResult(modulePath, result != null);
return result ?? AnalyzeTheOldWay(modulePath, context, lastWriteTime);
}
internal static bool ModuleAnalysisViaGetModuleRequired(object modulePathObj, bool hadCmdlets, bool hadFunctions, bool hadAliases)
{
var modulePath = modulePathObj as string;
if (modulePath == null)
return true;
if (modulePath.EndsWith(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase))
{
// A script module can't exactly define cmdlets, but it can import a binary module (as nested), so
// it can indirectly define cmdlets. And obviously a script module can define functions and aliases.
// If we got here, one of those is missing, so analysis is required.
return true;
}
if (modulePath.EndsWith(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase))
{
// A cdxml module can only define functions and aliases, so if we have both, no more analysis is required.
return !hadFunctions || !hadAliases;
}
if (modulePath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
// A dll just exports cmdlets, so if the manifest doesn't explicitly export any cmdlets,
// more analysis is required. If the module exports aliases, we can't discover that analyzing
// the binary, so aliases are always required to be explicit (no wildcards) in the manifest.
return !hadCmdlets;
}
// Any other extension (or no extension), just assume the worst and analyze the module
return true;
}
// Returns true if we need to analyze the manifest module in Get-Module because
// our quick and dirty module manifest analysis is missing something not easily
// discovered.
//
// TODO - psm1 modules are actually easily handled, so if we only saw a psm1 here,
// we should just analyze it and not fall back on Get-Module -List.
private static bool CheckModulesTypesInManifestAgainstExportedCommands(Hashtable moduleManifestProperties, bool hadCmdlets, bool hadFunctions, bool hadAliases)
{
var rootModule = moduleManifestProperties["RootModule"];
if (rootModule != null && ModuleAnalysisViaGetModuleRequired(rootModule, hadCmdlets, hadFunctions, hadAliases))
return true;
var moduleToProcess = moduleManifestProperties["ModuleToProcess"];
if (moduleToProcess != null && ModuleAnalysisViaGetModuleRequired(moduleToProcess, hadCmdlets, hadFunctions, hadAliases))
return true;
var nestedModules = moduleManifestProperties["NestedModules"];
if (nestedModules != null)
{
var nestedModule = nestedModules as string;
if (nestedModule != null)
{
return ModuleAnalysisViaGetModuleRequired(nestedModule, hadCmdlets, hadFunctions, hadAliases);
}
var nestedModuleArray = nestedModules as object[];
if (nestedModuleArray == null)
return true;
foreach (var element in nestedModuleArray)
{
if (ModuleAnalysisViaGetModuleRequired(element, hadCmdlets, hadFunctions, hadAliases))
return true;
}
}
return false;
}
private static bool AddPsd1EntryToResult(ConcurrentDictionary<string, CommandTypes> result, string command, CommandTypes commandTypeToAdd, ref bool sawWildcard)
{
if (WildcardPattern.ContainsWildcardCharacters(command))
{
sawWildcard = true;
return false;
}
// An empty string is one way of saying "no exported commands".
if (command.Length != 0)
{
CommandTypes commandTypes;
if (result.TryGetValue(command, out commandTypes))
{
commandTypes |= commandTypeToAdd;
}
else
{
commandTypes = commandTypeToAdd;
}
result[command] = commandTypes;
}
return true;
}
private static bool AddPsd1EntryToResult(ConcurrentDictionary<string, CommandTypes> result, object value, CommandTypes commandTypeToAdd, ref bool sawWildcard)
{
string command = value as string;
if (command != null)
{
return AddPsd1EntryToResult(result, command, commandTypeToAdd, ref sawWildcard);
}
object[] commands = value as object[];
if (commands != null)
{
foreach (var o in commands)
{
if (!AddPsd1EntryToResult(result, o, commandTypeToAdd, ref sawWildcard))
return false;
}
// An empty array is still success, that's how a manifest declares that
// no entries are exported (unlike the lack of an entry, or $null).
return true;
}
// Unknown type, let Get-Module -List deal with this manifest
return false;
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeScriptModule(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
var scriptAnalysis = ScriptAnalysis.Analyze(modulePath, context);
if (scriptAnalysis == null)
{
return null;
}
List<WildcardPattern> scriptAnalysisPatterns = new List<WildcardPattern>();
foreach (string discoveredCommandFilter in scriptAnalysis.DiscoveredCommandFilters)
{
scriptAnalysisPatterns.Add(new WildcardPattern(discoveredCommandFilter));
}
var result = new ConcurrentDictionary<string, CommandTypes>(3,
scriptAnalysis.DiscoveredExports.Count + scriptAnalysis.DiscoveredAliases.Count,
StringComparer.OrdinalIgnoreCase);
// Add any directly discovered exports
foreach (var command in scriptAnalysis.DiscoveredExports)
{
if (SessionStateUtilities.MatchesAnyWildcardPattern(command, scriptAnalysisPatterns, true))
{
if (command.IndexOfAny(InvalidCommandNameCharacters) < 0)
{
result[command] = CommandTypes.Function;
}
}
}
// Add the discovered aliases
foreach (var pair in scriptAnalysis.DiscoveredAliases)
{
var commandName = pair.Key;
// These are already filtered
if (commandName.IndexOfAny(InvalidCommandNameCharacters) < 0)
{
result.AddOrUpdate(commandName, CommandTypes.Alias,
(_, existingCommandType) => existingCommandType | CommandTypes.Alias);
}
}
// Add any files in PsScriptRoot if it added itself to the path
if (scriptAnalysis.AddsSelfToPath)
{
string baseDirectory = Path.GetDirectoryName(modulePath);
try
{
foreach (string item in Directory.GetFiles(baseDirectory, "*.ps1"))
{
var command = Path.GetFileNameWithoutExtension(item);
result.AddOrUpdate(command, CommandTypes.ExternalScript,
(_, existingCommandType) => existingCommandType | CommandTypes.ExternalScript);
}
}
catch (UnauthorizedAccessException)
{
// Consume this exception here
}
}
var exportedClasses = new ConcurrentDictionary<string, TypeAttributes>( /*concurrency*/
1, scriptAnalysis.DiscoveredClasses.Count, StringComparer.OrdinalIgnoreCase);
foreach (var exportedClass in scriptAnalysis.DiscoveredClasses)
{
exportedClasses[exportedClass.Name] = exportedClass.TypeAttributes;
}
var moduleCacheEntry = new ModuleCacheEntry
{
ModulePath = modulePath,
LastWriteTime = lastWriteTime,
Commands = result,
TypesAnalyzed = true,
Types = exportedClasses
};
s_cacheData.Entries[modulePath] = moduleCacheEntry;
return result;
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeXamlModule(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
return AnalyzeTheOldWay(modulePath, context, lastWriteTime);
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeCdxmlModule(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
return AnalyzeTheOldWay(modulePath, context, lastWriteTime);
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeDllModule(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
return AnalyzeTheOldWay(modulePath, context, lastWriteTime);
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeTheOldWay(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
try
{
// If we're already analyzing this module, let the recursion bottom out.
if (!s_modulesBeingAnalyzed.TryAdd(modulePath, modulePath))
{
ModuleIntrinsics.Tracer.WriteLine("{0} is already being analyzed. Exiting.", modulePath);
return null;
}
// Record that we're analyzing this specific module so that we don't get stuck in recursion
ModuleIntrinsics.Tracer.WriteLine("Started analysis: {0}", modulePath);
CallGetModuleDashList(context, modulePath);
ModuleCacheEntry moduleCacheEntry;
if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry))
{
return moduleCacheEntry.Commands;
}
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e);
// Catch-all OK, third-party call-out.
CommandProcessorBase.CheckForSevereException(e);
}
finally
{
ModuleIntrinsics.Tracer.WriteLine("Finished analysis: {0}", modulePath);
s_modulesBeingAnalyzed.TryRemove(modulePath, out modulePath);
}
return null;
}
/// <summary>
/// Return the exported types for a specific module.
/// If the module is already cache, return from cache, else cache the module.
/// Also re-cache the module if the cached item is stale.
/// </summary>
/// <param name="modulePath">Path to the module to get exported types from.</param>
/// <param name="context">Current Context</param>
/// <returns></returns>
internal static ConcurrentDictionary<string, TypeAttributes> GetExportedClasses(string modulePath, ExecutionContext context)
{
DateTime lastWriteTime;
ModuleCacheEntry moduleCacheEntry;
if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry) && moduleCacheEntry.TypesAnalyzed)
{
return moduleCacheEntry.Types;
}
try
{
CallGetModuleDashList(context, modulePath);
if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry))
{
return moduleCacheEntry.Types;
}
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e);
// Catch-all OK, third-party call-out.
CommandProcessorBase.CheckForSevereException(e);
}
return null;
}
internal static void CacheModuleExports(PSModuleInfo module, ExecutionContext context)
{
ModuleIntrinsics.Tracer.WriteLine("Requested caching for {0}", module.Name);
DateTime lastWriteTime;
ModuleCacheEntry moduleCacheEntry;
GetModuleEntryFromCache(module.Path, out lastWriteTime, out moduleCacheEntry);
var realExportedCommands = module.ExportedCommands;
var realExportedClasses = module.GetExportedTypeDefinitions();
ConcurrentDictionary<string, CommandTypes> exportedCommands;
ConcurrentDictionary<string, TypeAttributes> exportedClasses;
// First see if the existing module info is sufficient. GetModuleEntryFromCache does LastWriteTime
// verification, so this will also return nothing if the cache is out of date or corrupt.
if (moduleCacheEntry != null)
{
bool needToUpdate = false;
// We need to iterate and check as exportedCommands will have more item as it can have aliases as well.
exportedCommands = moduleCacheEntry.Commands;
foreach (var pair in realExportedCommands)
{
var commandName = pair.Key;
var realCommandType = pair.Value.CommandType;
CommandTypes commandType;
if (!exportedCommands.TryGetValue(commandName, out commandType) || commandType != realCommandType)
{
needToUpdate = true;
break;
}
}
exportedClasses = moduleCacheEntry.Types;
foreach (var pair in realExportedClasses)
{
var className = pair.Key;
var realTypeAttributes = pair.Value.TypeAttributes;
TypeAttributes typeAttributes;
if (!exportedClasses.TryGetValue(className, out typeAttributes) ||
typeAttributes != realTypeAttributes)
{
needToUpdate = true;
break;
}
}
// Update or not, we've analyzed commands and types now.
moduleCacheEntry.TypesAnalyzed = true;
if (!needToUpdate)
{
ModuleIntrinsics.Tracer.WriteLine("Existing cached info up-to-date. Skipping.");
return;
}
exportedCommands.Clear();
exportedClasses.Clear();
}
else
{
exportedCommands = new ConcurrentDictionary<string, CommandTypes>(3, realExportedCommands.Count, StringComparer.OrdinalIgnoreCase);
exportedClasses = new ConcurrentDictionary<string, TypeAttributes>(1, realExportedClasses.Count, StringComparer.OrdinalIgnoreCase);
moduleCacheEntry = new ModuleCacheEntry
{
ModulePath = module.Path,
LastWriteTime = lastWriteTime,
Commands = exportedCommands,
TypesAnalyzed = true,
Types = exportedClasses
};
moduleCacheEntry = s_cacheData.Entries.GetOrAdd(module.Path, moduleCacheEntry);
}
// We need to update the cache
foreach (var exportedCommand in realExportedCommands.Values)
{
ModuleIntrinsics.Tracer.WriteLine("Caching command: {0}", exportedCommand.Name);
exportedCommands.GetOrAdd(exportedCommand.Name, exportedCommand.CommandType);
}
foreach (var pair in realExportedClasses)
{
var className = pair.Key;
ModuleIntrinsics.Tracer.WriteLine("Caching command: {0}", className);
moduleCacheEntry.Types.AddOrUpdate(className, pair.Value.TypeAttributes, (k, t) => t);
}
s_cacheData.QueueSerialization();
}
private static void CallGetModuleDashList(ExecutionContext context, string modulePath)
{
CommandInfo commandInfo = new CmdletInfo("Get-Module", typeof(GetModuleCommand), null, null, context);
Command getModuleCommand = new Command(commandInfo);
try
{
PowerShell.Create(RunspaceMode.CurrentRunspace)
.AddCommand(getModuleCommand)
.AddParameter("List", true)
.AddParameter("ErrorAction", ActionPreference.Ignore)
.AddParameter("WarningAction", ActionPreference.Ignore)
.AddParameter("InformationAction", ActionPreference.Ignore)
.AddParameter("Verbose", false)
.AddParameter("Debug", false)
.AddParameter("Name", modulePath)
.Invoke();
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e);
// Catch-all OK, third-party call-out.
CommandProcessorBase.CheckForSevereException(e);
}
}
private static bool GetModuleEntryFromCache(string modulePath, out DateTime lastWriteTime, out ModuleCacheEntry moduleCacheEntry)
{
try
{
lastWriteTime = new FileInfo(modulePath).LastWriteTime;
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Exception checking LastWriteTime on module {0}: {1}", modulePath, e.Message);
lastWriteTime = DateTime.MinValue;
}
if (s_cacheData.Entries.TryGetValue(modulePath, out moduleCacheEntry))
{
if (lastWriteTime == moduleCacheEntry.LastWriteTime)
{
return true;
}
ModuleIntrinsics.Tracer.WriteLine("{0}: cache entry out of date, cached on {1}, last updated on {2}",
modulePath, moduleCacheEntry.LastWriteTime, lastWriteTime);
s_cacheData.Entries.TryRemove(modulePath, out moduleCacheEntry);
}
moduleCacheEntry = null;
return false;
}
}
internal class AnalysisCacheData
{
private static byte[] GetHeader()
{
return new byte[]
{
0x50, 0x53, 0x4d, 0x4f, 0x44, 0x55, 0x4c, 0x45, 0x43, 0x41, 0x43, 0x48, 0x45, // PSMODULECACHE
0x01 // version #
};
}
// The last time the index was maintained.
public DateTime LastReadTime { get; set; }
public ConcurrentDictionary<string, ModuleCacheEntry> Entries { get; set; }
private int _saveCacheToDiskQueued;
public void QueueSerialization()
{
// We expect many modules to rapidly call for serialization.
// Instead of doing it right away, we'll queue a task that starts writing
// after it seems like we've stopped adding stuff to write out. This is
// avoids blocking the pipeline thread waiting for the write to finish.
// We want to make sure we only queue one task.
if (Interlocked.Increment(ref _saveCacheToDiskQueued) == 1)
{
Task.Run(async delegate
{
// Wait a while before assuming we've finished the updates,
// writing the cache out in a timely matter isn't too important
// now anyway.
await Task.Delay(10000);
int counter1, counter2;
do
{
// Check the counter a couple times with a delay,
// if it's stable, then proceed with writing.
counter1 = _saveCacheToDiskQueued;
await Task.Delay(3000);
counter2 = _saveCacheToDiskQueued;
} while (counter1 != counter2);
Serialize(s_cacheStoreLocation);
});
}
}
// Remove entries that are not needed anymore, e.g. if a module was removed.
// If anything is removed, save the cache.
private void Cleanup()
{
Diagnostics.Assert(Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") == null,
"Caller to check environment variable before calling");
bool removedSomething = false;
var keys = Entries.Keys;
foreach (var key in keys)
{
if (!Utils.NativeFileExists(key))
{
ModuleCacheEntry unused;
removedSomething |= Entries.TryRemove(key, out unused);
}
}
if (removedSomething)
{
QueueSerialization();
}
}
private static unsafe void Write(int val, byte[] bytes, FileStream stream)
{
Diagnostics.Assert(bytes.Length >= 4, "Must pass a large enough byte array");
fixed (byte* b = bytes) *((int*)b) = val;
stream.Write(bytes, 0, 4);
}
private static unsafe void Write(long val, byte[] bytes, FileStream stream)
{
Diagnostics.Assert(bytes.Length >= 8, "Must pass a large enough byte array");
fixed (byte* b = bytes) *((long*)b) = val;
stream.Write(bytes, 0, 8);
}
private static void Write(string val, byte[] bytes, FileStream stream)
{
Write(val.Length, bytes, stream);
bytes = Encoding.UTF8.GetBytes(val);
stream.Write(bytes, 0, bytes.Length);
}
private void Serialize(string filename)
{
AnalysisCacheData fromOtherProcess = null;
try
{
if (Utils.NativeFileExists(filename))
{
var fileLastWriteTime = new FileInfo(filename).LastWriteTime;
if (fileLastWriteTime > this.LastReadTime)
{
fromOtherProcess = Deserialize(filename);
}
}
else
{
// Make sure the folder exists
var folder = Path.GetDirectoryName(filename);
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
}
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Exception checking module analysis cache {0}: {1} ", filename, e.Message);
}
if (fromOtherProcess != null)
{
// We should merge with what another process wrote so we don't clobber useful analysis
foreach (var otherEntryPair in fromOtherProcess.Entries)
{
var otherModuleName = otherEntryPair.Key;
var otherEntry = otherEntryPair.Value;
ModuleCacheEntry thisEntry;
if (Entries.TryGetValue(otherModuleName, out thisEntry))
{
if (otherEntry.LastWriteTime > thisEntry.LastWriteTime)
{
// The other entry is newer, take it over ours
Entries[otherModuleName] = otherEntry;
}
}
else
{
Entries[otherModuleName] = otherEntry;
}
}
}
// "PSMODULECACHE" -> 13 bytes
// byte ( 1 byte) -> version
// int ( 4 bytes) -> count of entries
// entries (?? bytes) -> all entries
//
// each entry is
// DateTime ( 8 bytes) -> last write time for module file
// int ( 4 bytes) -> path length
// string (?? bytes) -> utf8 encoded path
// int ( 4 bytes) -> count of commands
// commands (?? bytes) -> all commands
// int ( 4 bytes) -> count of types, -1 means unanalyzed (and 0 items serialized)
// types (?? bytes) -> all types
//
// each command is
// int ( 4 bytes) -> command name length
// string (?? bytes) -> utf8 encoded command name
// int ( 4 bytes) -> CommandTypes enum
//
// each type is
// int ( 4 bytes) -> type name length
// string (?? bytes) -> utf8 encoded type name
// int ( 4 bytes) -> type attributes
try
{
var bytes = new byte[8];
using (var stream = File.Create(filename))
{
var headerBytes = GetHeader();
stream.Write(headerBytes, 0, headerBytes.Length);
// Count of entries
Write(Entries.Count, bytes, stream);
foreach (var pair in Entries.ToArray())
{
var path = pair.Key;
var entry = pair.Value;
// Module last write time
Write(entry.LastWriteTime.Ticks, bytes, stream);
// Module path
Write(path, bytes, stream);
// Commands
var commandPairs = entry.Commands.ToArray();
Write(commandPairs.Length, bytes, stream);
foreach (var command in commandPairs)
{
Write(command.Key, bytes, stream);
Write((int)command.Value, bytes, stream);
}
// Types
var typePairs = entry.Types.ToArray();
Write(entry.TypesAnalyzed ? typePairs.Length : -1, bytes, stream);
foreach (var type in typePairs)
{
Write(type.Key, bytes, stream);
Write((int)type.Value, bytes, stream);
}
}
}
// We just wrote the file, note this so we can detect writes from another process
LastReadTime = new FileInfo(filename).LastWriteTime;
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Exception writing module analysis cache {0}: {1} ", filename, e.Message);
}
// Reset our counter so we can write again if asked.
Interlocked.Exchange(ref _saveCacheToDiskQueued, 0);
}
private const string TruncatedErrorMessage = "module cache file appears truncated";
private const string InvalidSignatureErrorMessage = "module cache signature not valid";
private const string PossibleCorruptionErrorMessage = "possible corruption in module cache";
private static unsafe long ReadLong(FileStream stream, byte[] bytes)
{
Diagnostics.Assert(bytes.Length >= 8, "Must pass a large enough byte array");
if (stream.Read(bytes, 0, 8) != 8)
throw new Exception(TruncatedErrorMessage);
fixed (byte* b = bytes)
return *(long*)b;
}
private static unsafe int ReadInt(FileStream stream, byte[] bytes)
{
Diagnostics.Assert(bytes.Length >= 4, "Must pass a large enough byte array");
if (stream.Read(bytes, 0, 4) != 4)
throw new Exception(TruncatedErrorMessage);
fixed (byte* b = bytes)
return *(int*)b;
}
private static string ReadString(FileStream stream, ref byte[] bytes)
{
int length = ReadInt(stream, bytes);
if (length > 10 * 1024)
throw new Exception(PossibleCorruptionErrorMessage);
if (length > bytes.Length)
bytes = new byte[length];
if (stream.Read(bytes, 0, length) != length)
throw new Exception(TruncatedErrorMessage);
return Encoding.UTF8.GetString(bytes, 0, length);
}
private static void ReadHeader(FileStream stream, byte[] bytes)
{
var headerBytes = GetHeader();
var length = headerBytes.Length;
Diagnostics.Assert(bytes.Length >= length, "must pass a large enough byte array");
if (stream.Read(bytes, 0, length) != length)
throw new Exception(TruncatedErrorMessage);
for (int i = 0; i < length; i++)
{
if (bytes[i] != headerBytes[i])
{
throw new Exception(InvalidSignatureErrorMessage);
}
}
// No need to return - we don't use it other than to detect the correct file format
}
public static AnalysisCacheData Deserialize(string filename)
{
using (var stream = File.OpenRead(filename))
{
var result = new AnalysisCacheData { LastReadTime = DateTime.Now };
var bytes = new byte[1024];
// Header
// "PSMODULECACHE" -> 13 bytes
// byte ( 1 byte) -> version
ReadHeader(stream, bytes);
// int ( 4 bytes) -> count of entries
int entries = ReadInt(stream, bytes);
if (entries > 20 * 1024)
throw new Exception(PossibleCorruptionErrorMessage);
result.Entries = new ConcurrentDictionary<string, ModuleCacheEntry>(/*concurrency*/3, entries, StringComparer.OrdinalIgnoreCase);
// entries (?? bytes) -> all entries
while (entries > 0)
{
// DateTime ( 8 bytes) -> last write time for module file
var lastWriteTime = new DateTime(ReadLong(stream, bytes));
// int ( 4 bytes) -> path length
// string (?? bytes) -> utf8 encoded path
var path = ReadString(stream, ref bytes);
// int ( 4 bytes) -> count of commands
var countItems = ReadInt(stream, bytes);
if (countItems > 20 * 1024)
throw new Exception(PossibleCorruptionErrorMessage);
var commands = new ConcurrentDictionary<string, CommandTypes>(/*concurrency*/3, countItems, StringComparer.OrdinalIgnoreCase);
// commands (?? bytes) -> all commands
while (countItems > 0)
{
// int ( 4 bytes) -> command name length
// string (?? bytes) -> utf8 encoded command name
var commandName = ReadString(stream, ref bytes);
// int ( 4 bytes) -> CommandTypes enum
var commandTypes = (CommandTypes)ReadInt(stream, bytes);
// Ignore empty entries (possible corruption in the cache or bug?)
if (!string.IsNullOrWhiteSpace(commandName))
commands[commandName] = commandTypes;
countItems -= 1;
}
// int ( 4 bytes) -> count of types
countItems = ReadInt(stream, bytes);
bool typesAnalyzed = countItems != -1;
if (!typesAnalyzed)
countItems = 0;
if (countItems > 20 * 1024)
throw new Exception(PossibleCorruptionErrorMessage);
var types = new ConcurrentDictionary<string, TypeAttributes>(1, countItems, StringComparer.OrdinalIgnoreCase);
// types (?? bytes) -> all types
while (countItems > 0)
{
// int ( 4 bytes) -> type name length
// string (?? bytes) -> utf8 encoded type name
var typeName = ReadString(stream, ref bytes);
// int ( 4 bytes) -> type attributes
var typeAttributes = (TypeAttributes)ReadInt(stream, bytes);
// Ignore empty entries (possible corruption in the cache or bug?)
if (!string.IsNullOrWhiteSpace(typeName))
types[typeName] = typeAttributes;
countItems -= 1;
}
var entry = new ModuleCacheEntry
{
ModulePath = path,
LastWriteTime = lastWriteTime,
Commands = commands,
TypesAnalyzed = typesAnalyzed,
Types = types
};
result.Entries[path] = entry;
entries -= 1;
}
if (Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") == null)
{
Task.Delay(10000).ContinueWith(_ => result.Cleanup());
}
return result;
}
}
internal static AnalysisCacheData Get()
{
int retryCount = 3;
do
{
try
{
if (Utils.NativeFileExists(s_cacheStoreLocation))
{
return Deserialize(s_cacheStoreLocation);
}
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Exception checking module analysis cache: " + e.Message);
if ((object)e.Message == (object)TruncatedErrorMessage
|| (object)e.Message == (object)InvalidSignatureErrorMessage
|| (object)e.Message == (object)PossibleCorruptionErrorMessage)
{
// Don't retry if we detected something is wrong with the file
// (as opposed to the file being locked or something else)
break;
}
}
retryCount -= 1;
Thread.Sleep(25); // Sleep a bit to give time for another process to finish writing the cache
} while (retryCount > 0);
return new AnalysisCacheData
{
LastReadTime = DateTime.Now,
// Capacity set to 100 - a bit bigger than the # of modules on a default Win10 client machine
// Concurrency=3 to not create too many locks, contention is unclear, but the old code had a single lock
Entries = new ConcurrentDictionary<string, ModuleCacheEntry>(/*concurrency*/3, /*capacity*/100, StringComparer.OrdinalIgnoreCase)
};
}
private AnalysisCacheData()
{
}
private static readonly string s_cacheStoreLocation;
static AnalysisCacheData()
{
s_cacheStoreLocation =
Environment.GetEnvironmentVariable("PSModuleAnalysisCachePath") ??
#if UNIX
Path.Combine(Platform.SelectProductNameForDirectory(Platform.XDG_Type.CACHE), "ModuleAnalysisCache");
#else
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\Windows\PowerShell\ModuleAnalysisCache");
#endif
}
}
[DebuggerDisplay("ModulePath = {ModulePath}")]
internal class ModuleCacheEntry
{
public DateTime LastWriteTime;
public string ModulePath;
public bool TypesAnalyzed;
public ConcurrentDictionary<string, CommandTypes> Commands;
public ConcurrentDictionary<string, TypeAttributes> Types;
}
} // System.Management.Automation
| |
/*
* Muhimbi PDF
*
* Convert, Merge, Watermark, Secure and OCR files.
*
* OpenAPI spec version: 9.15
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Muhimbi.PDF.Online.Client.Client;
using Muhimbi.PDF.Online.Client.Model;
namespace Muhimbi.PDF.Online.Client.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IOCRApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Convert to OCRed PDF
/// </summary>
/// <remarks>
/// Convert a file to an OCRed PDF.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>OperationResponse</returns>
OperationResponse OcrPdf (OcrPdfData inputData);
/// <summary>
/// Convert to OCRed PDF
/// </summary>
/// <remarks>
/// Convert a file to an OCRed PDF.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>ApiResponse of OperationResponse</returns>
ApiResponse<OperationResponse> OcrPdfWithHttpInfo (OcrPdfData inputData);
/// <summary>
/// Extract text using OCR
/// </summary>
/// <remarks>
/// Extract text from a file using OCR.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>OcrOperationResponse</returns>
OcrOperationResponse OcrText (OcrTextData inputData);
/// <summary>
/// Extract text using OCR
/// </summary>
/// <remarks>
/// Extract text from a file using OCR.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>ApiResponse of OcrOperationResponse</returns>
ApiResponse<OcrOperationResponse> OcrTextWithHttpInfo (OcrTextData inputData);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Convert to OCRed PDF
/// </summary>
/// <remarks>
/// Convert a file to an OCRed PDF.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of OperationResponse</returns>
System.Threading.Tasks.Task<OperationResponse> OcrPdfAsync (OcrPdfData inputData);
/// <summary>
/// Convert to OCRed PDF
/// </summary>
/// <remarks>
/// Convert a file to an OCRed PDF.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of ApiResponse (OperationResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<OperationResponse>> OcrPdfAsyncWithHttpInfo (OcrPdfData inputData);
/// <summary>
/// Extract text using OCR
/// </summary>
/// <remarks>
/// Extract text from a file using OCR.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of OcrOperationResponse</returns>
System.Threading.Tasks.Task<OcrOperationResponse> OcrTextAsync (OcrTextData inputData);
/// <summary>
/// Extract text using OCR
/// </summary>
/// <remarks>
/// Extract text from a file using OCR.
/// </remarks>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of ApiResponse (OcrOperationResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<OcrOperationResponse>> OcrTextAsyncWithHttpInfo (OcrTextData inputData);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class OCRApi : IOCRApi
{
private Muhimbi.PDF.Online.Client.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="OCRApi"/> class.
/// </summary>
/// <returns></returns>
public OCRApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Muhimbi.PDF.Online.Client.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="OCRApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public OCRApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Muhimbi.PDF.Online.Client.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Muhimbi.PDF.Online.Client.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Convert to OCRed PDF Convert a file to an OCRed PDF.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>OperationResponse</returns>
public OperationResponse OcrPdf (OcrPdfData inputData)
{
ApiResponse<OperationResponse> localVarResponse = OcrPdfWithHttpInfo(inputData);
return localVarResponse.Data;
}
/// <summary>
/// Convert to OCRed PDF Convert a file to an OCRed PDF.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>ApiResponse of OperationResponse</returns>
public ApiResponse< OperationResponse > OcrPdfWithHttpInfo (OcrPdfData inputData)
{
// verify the required parameter 'inputData' is set
if (inputData == null)
throw new ApiException(400, "Missing required parameter 'inputData' when calling OCRApi->OcrPdf");
var localVarPath = "/v1/operations/ocr_pdf";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (inputData != null && inputData.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter
}
else
{
localVarPostBody = inputData; // byte array
}
// authentication (oauth2_auth) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key")))
{
localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("OcrPdf", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OperationResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperationResponse)));
}
/// <summary>
/// Convert to OCRed PDF Convert a file to an OCRed PDF.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of OperationResponse</returns>
public async System.Threading.Tasks.Task<OperationResponse> OcrPdfAsync (OcrPdfData inputData)
{
ApiResponse<OperationResponse> localVarResponse = await OcrPdfAsyncWithHttpInfo(inputData);
return localVarResponse.Data;
}
/// <summary>
/// Convert to OCRed PDF Convert a file to an OCRed PDF.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of ApiResponse (OperationResponse)</returns>
public async System.Threading.Tasks.Task<ApiResponse<OperationResponse>> OcrPdfAsyncWithHttpInfo (OcrPdfData inputData)
{
// verify the required parameter 'inputData' is set
if (inputData == null)
throw new ApiException(400, "Missing required parameter 'inputData' when calling OCRApi->OcrPdf");
var localVarPath = "/v1/operations/ocr_pdf";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (inputData != null && inputData.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter
}
else
{
localVarPostBody = inputData; // byte array
}
// authentication (oauth2_auth) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key")))
{
localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("OcrPdf", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OperationResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperationResponse)));
}
/// <summary>
/// Extract text using OCR Extract text from a file using OCR.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>OcrOperationResponse</returns>
public OcrOperationResponse OcrText (OcrTextData inputData)
{
ApiResponse<OcrOperationResponse> localVarResponse = OcrTextWithHttpInfo(inputData);
return localVarResponse.Data;
}
/// <summary>
/// Extract text using OCR Extract text from a file using OCR.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>ApiResponse of OcrOperationResponse</returns>
public ApiResponse< OcrOperationResponse > OcrTextWithHttpInfo (OcrTextData inputData)
{
// verify the required parameter 'inputData' is set
if (inputData == null)
throw new ApiException(400, "Missing required parameter 'inputData' when calling OCRApi->OcrText");
var localVarPath = "/v1/operations/ocr_text";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (inputData != null && inputData.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter
}
else
{
localVarPostBody = inputData; // byte array
}
// authentication (oauth2_auth) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key")))
{
localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("OcrText", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OcrOperationResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OcrOperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OcrOperationResponse)));
}
/// <summary>
/// Extract text using OCR Extract text from a file using OCR.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of OcrOperationResponse</returns>
public async System.Threading.Tasks.Task<OcrOperationResponse> OcrTextAsync (OcrTextData inputData)
{
ApiResponse<OcrOperationResponse> localVarResponse = await OcrTextAsyncWithHttpInfo(inputData);
return localVarResponse.Data;
}
/// <summary>
/// Extract text using OCR Extract text from a file using OCR.
/// </summary>
/// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="inputData"></param>
/// <returns>Task of ApiResponse (OcrOperationResponse)</returns>
public async System.Threading.Tasks.Task<ApiResponse<OcrOperationResponse>> OcrTextAsyncWithHttpInfo (OcrTextData inputData)
{
// verify the required parameter 'inputData' is set
if (inputData == null)
throw new ApiException(400, "Missing required parameter 'inputData' when calling OCRApi->OcrText");
var localVarPath = "/v1/operations/ocr_text";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (inputData != null && inputData.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter
}
else
{
localVarPostBody = inputData; // byte array
}
// authentication (oauth2_auth) required
// oauth required
if (!String.IsNullOrEmpty(Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key")))
{
localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("OcrText", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OcrOperationResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OcrOperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OcrOperationResponse)));
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: AssertionFactory.cs 640 2009-06-01 17:22:02Z azizatif $")]
namespace Elmah.Assertions
{
#region Imports
using System;
using System.ComponentModel;
using System.Configuration;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Collections.Generic;
#endregion
/// <summary>
/// Represents the method that will be responsible for creating an
/// assertion object and initializing it from an XML configuration
/// element.
/// </summary>
public delegate IAssertion AssertionFactoryHandler(XmlElement config);
/// <summary>
/// Holds factory methods for creating configured assertion objects.
/// </summary>
public static class AssertionFactory
{
public static IAssertion assert_is_null(IContextExpression binding)
{
return new IsNullAssertion(binding);
}
public static IAssertion assert_is_not_null(IContextExpression binding)
{
return new UnaryNotAssertion(assert_is_null(binding));
}
public static IAssertion assert_equal(IContextExpression binding, TypeCode type, string value)
{
return new ComparisonAssertion(ComparisonResults.Equal, binding, type, value);
}
public static IAssertion assert_not_equal(IContextExpression binding, TypeCode type, string value)
{
return new UnaryNotAssertion(assert_equal(binding, type, value));
}
public static IAssertion assert_lesser(IContextExpression binding, TypeCode type, string value)
{
return new ComparisonAssertion(ComparisonResults.Lesser, binding, type, value);
}
public static IAssertion assert_lesser_or_equal(IContextExpression binding, TypeCode type, string value)
{
return new ComparisonAssertion(ComparisonResults.LesserOrEqual, binding, type, value);
}
public static IAssertion assert_greater(IContextExpression binding, TypeCode type, string value)
{
return new ComparisonAssertion(ComparisonResults.Greater, binding, type, value);
}
public static IAssertion assert_greater_or_equal(IContextExpression binding, TypeCode type, string value)
{
return new ComparisonAssertion(ComparisonResults.GreaterOrEqual, binding, type, value);
}
public static IAssertion assert_and(XmlElement config)
{
return LogicalAssertion.LogicalAnd(Create(config.ChildNodes));
}
public static IAssertion assert_or(XmlElement config)
{
return LogicalAssertion.LogicalOr(Create(config.ChildNodes));
}
public static IAssertion assert_not(XmlElement config)
{
return LogicalAssertion.LogicalNot(Create(config.ChildNodes));
}
public static IAssertion assert_is_type(IContextExpression binding, Type type)
{
return new TypeAssertion(binding, type, /* byCompatibility */ false);
}
public static IAssertion assert_is_type_compatible(IContextExpression binding, Type type)
{
return new TypeAssertion(binding, type, /* byCompatibility */ true);
}
public static IAssertion assert_regex(IContextExpression binding, string pattern, bool caseSensitive, bool dontCompile)
{
if ((pattern ?? string.Empty).Length == 0)
return StaticAssertion.False;
//
// NOTE: There is an assumption here that most uses of this
// assertion will be for culture-insensitive matches. Since
// it is difficult to imagine all the implications of involving
// a culture at this point, it seems safer to just err with the
// invariant culture settings.
//
var options = RegexOptions.CultureInvariant;
if (!caseSensitive)
options |= RegexOptions.IgnoreCase;
if (!dontCompile)
options |= RegexOptions.Compiled;
return new RegexMatchAssertion(binding, new Regex(pattern, options));
}
public static IAssertion assert_jscript(XmlElement config)
{
if (config == null) throw new ArgumentNullException("config");
//
// The expression can be specified via an attribute or a
// a child element named "expression". The element form takes
// precedence.
//
// TODO More rigorous validation
// For example, expression should not appear as an attribute and
// a child node. Also multiple child expressions should result in
// an error.
string expression = null;
var expressionElement = config["expression"];
if (expressionElement != null)
expression = expressionElement.InnerText;
if (expression == null)
expression = config.GetAttribute("expression");
return new JScriptAssertion(
expression,
DeserializeStringArray(config, "assemblies", "assembly", "name"),
DeserializeStringArray(config, "imports", "import", "namespace"));
}
public static IAssertion Create(XmlElement config)
{
if (config == null)
throw new ArgumentNullException("config");
try
{
return CreateImpl(config);
}
catch (ConfigurationException)
{
throw;
}
catch (Exception e)
{
throw new ConfigurationException(e.Message, e);
}
}
public static IAssertion[] Create(XmlNodeList nodes)
{
if (nodes == null)
throw new ArgumentNullException("nodes");
//
// First count the number of elements, which will be used to
// allocate the array at its correct and final size.
//
var elementCount = 0;
foreach (XmlNode child in nodes)
{
var nodeType = child.NodeType;
//
// Skip comments and whitespaces.
//
if (nodeType == XmlNodeType.Comment || nodeType == XmlNodeType.Whitespace)
continue;
//
// Otherwise all elements only.
//
if (nodeType != XmlNodeType.Element)
{
throw new ConfigurationException(
string.Format("Unexpected type of node ({0}).", nodeType.ToString()),
child);
}
elementCount++;
}
//
// In the second pass, create and configure the assertions
// from each element.
//
var assertions = new IAssertion[elementCount];
elementCount = 0;
foreach (XmlNode node in nodes)
{
if (node.NodeType == XmlNodeType.Element)
assertions[elementCount++] = Create((XmlElement) node);
}
return assertions;
}
private static IAssertion CreateImpl(XmlElement config)
{
Debug.Assert(config != null);
var name = "assert_" + config.LocalName;
if (name.IndexOf('-') > 0)
name = name.Replace("-", "_");
Type factoryType;
var xmlns = config.NamespaceURI ?? string.Empty;
if (xmlns.Length > 0)
{
string assemblyName, ns;
if (!DecodeClrTypeNamespaceFromXmlNamespace(xmlns, out ns, out assemblyName)
|| ns.Length == 0 || assemblyName.Length == 0)
{
throw new ConfigurationException(string.Format(
"Error decoding CLR type namespace and assembly from the XML namespace '{0}'.", xmlns));
}
var assembly = Assembly.Load(assemblyName);
factoryType = assembly.GetType(ns + ".AssertionFactory", /* throwOnError */ true);
}
else
{
factoryType = typeof(AssertionFactory);
}
var method = factoryType.GetMethod(name, BindingFlags.Public | BindingFlags.Static);
if (method == null)
{
throw new MissingMemberException(string.Format(
"{0} does not have a method named {1}. " +
"Ensure that the method is named correctly and that it is public and static.",
factoryType, name));
}
var parameters = method.GetParameters();
if (parameters.Length == 1
&& parameters[0].ParameterType == typeof(XmlElement)
&& method.ReturnType == typeof(IAssertion))
{
var handler = (AssertionFactoryHandler) Delegate.CreateDelegate(typeof(AssertionFactoryHandler), factoryType, name);
return handler(config); // TODO Check if Delegate.CreateDelegate could return null
}
return (IAssertion) method.Invoke(null, ParseArguments(method, config));
}
private static object[] ParseArguments(MethodInfo method, XmlElement config)
{
Debug.Assert(method != null);
Debug.Assert(config != null);
var parameters = method.GetParameters();
var args = new object[parameters.Length];
foreach (var parameter in parameters)
args[parameter.Position] = ParseArgument(parameter, config);
return args;
}
private static readonly string[] _truths = new[] { "true", "yes", "on", "1" }; // TODO Remove duplication with SecurityConfiguration
private static object ParseArgument(ParameterInfo parameter, XmlElement config)
{
Debug.Assert(parameter != null);
Debug.Assert(config != null);
var name = parameter.Name;
var type = parameter.ParameterType;
string text;
var attribute = config.GetAttributeNode(name);
if (attribute != null)
{
text = attribute.Value;
}
else
{
var element = config[name];
if (element == null)
return null;
text = element.InnerText;
}
if (type == typeof(IContextExpression))
return new WebDataBindingExpression(text);
if (type == typeof(Type))
return Type.GetType(text, /* throwOnError */ true, /* ignoreCase */ false);
if (type == typeof(bool))
{
text = text.Trim().ToLowerInvariant();
return Boolean.TrueString.Equals(StringTranslation.Translate(Boolean.TrueString, text, _truths));
}
var converter = TypeDescriptor.GetConverter(type);
return converter.ConvertFromInvariantString(text);
}
/// <remarks>
/// Ideally, we would be able to use SoapServices.DecodeXmlNamespaceForClrTypeNamespace
/// but that requires a link demand permission that will fail in partially trusted
/// environments such as ASP.NET medium trust.
/// </remarks>
private static bool DecodeClrTypeNamespaceFromXmlNamespace(string xmlns, out string typeNamespace, out string assemblyName)
{
Debug.Assert(xmlns != null);
assemblyName = string.Empty;
typeNamespace = string.Empty;
const string assemblyNS = "http://schemas.microsoft.com/clr/assem/";
const string namespaceNS = "http://schemas.microsoft.com/clr/ns/";
const string fullNS = "http://schemas.microsoft.com/clr/nsassem/";
if (OrdinalStringStartsWith(xmlns, assemblyNS))
{
assemblyName = HttpUtility.UrlDecode(xmlns.Substring(assemblyNS.Length));
return assemblyName.Length > 0;
}
if (OrdinalStringStartsWith(xmlns, namespaceNS))
{
typeNamespace = xmlns.Substring(namespaceNS.Length);
return typeNamespace.Length > 0;
}
if (OrdinalStringStartsWith(xmlns, fullNS))
{
var index = xmlns.IndexOf("/", fullNS.Length);
typeNamespace = xmlns.Substring(fullNS.Length, index - fullNS.Length);
assemblyName = HttpUtility.UrlDecode(xmlns.Substring(index + 1));
return assemblyName.Length > 0 && typeNamespace.Length > 0;
}
return false;
}
private static bool OrdinalStringStartsWith(string s, string prefix)
{
Debug.Assert(s != null);
Debug.Assert(prefix != null);
return s.Length >= prefix.Length &&
string.CompareOrdinal(s.Substring(0, prefix.Length), prefix) == 0;
}
private static string[] DeserializeStringArray(XmlElement config,
string containerName, string elementName, string valueName)
{
Debug.Assert(config != null);
Debug.AssertStringNotEmpty(containerName);
Debug.AssertStringNotEmpty(elementName);
Debug.AssertStringNotEmpty(valueName);
var list = new List<string>(4);
var xpath = containerName + "/" + elementName + "/@" + valueName;
foreach (XmlAttribute attribute in config.SelectNodes(xpath))
{
var value = attribute.Value ?? string.Empty;
if (value.Length > 0)
list.Add(attribute.Value);
}
return list.ToArray();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace BioMarket.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.Routing
{
internal class RoutePatternMatcher
{
// Perf: This is a cache to avoid looking things up in 'Defaults' each request.
private readonly bool[] _hasDefaultValue;
private readonly object[] _defaultValues;
public RoutePatternMatcher(
RoutePattern pattern,
RouteValueDictionary defaults)
{
if (pattern == null)
{
throw new ArgumentNullException(nameof(pattern));
}
RoutePattern = pattern;
Defaults = defaults ?? new RouteValueDictionary();
// Perf: cache the default value for each parameter (other than complex segments).
_hasDefaultValue = new bool[RoutePattern.PathSegments.Count];
_defaultValues = new object[RoutePattern.PathSegments.Count];
for (var i = 0; i < RoutePattern.PathSegments.Count; i++)
{
var segment = RoutePattern.PathSegments[i];
if (!segment.IsSimple)
{
continue;
}
var part = segment.Parts[0];
if (!part.IsParameter)
{
continue;
}
var parameter = (RoutePatternParameterPart)part;
if (Defaults.TryGetValue(parameter.Name, out var value))
{
_hasDefaultValue[i] = true;
_defaultValues[i] = value;
}
}
}
public RouteValueDictionary Defaults { get; }
public RoutePattern RoutePattern { get; }
public bool TryMatch(PathString path, RouteValueDictionary values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
var i = 0;
var pathTokenizer = new PathTokenizer(path);
// Perf: We do a traversal of the request-segments + route-segments twice.
//
// For most segment-types, we only really need to any work on one of the two passes.
//
// On the first pass, we're just looking to see if there's anything that would disqualify us from matching.
// The most common case would be a literal segment that doesn't match.
//
// On the second pass, we're almost certainly going to match the URL, so go ahead and allocate the 'values'
// and start capturing strings.
foreach (var stringSegment in pathTokenizer)
{
if (stringSegment.Length == 0)
{
return false;
}
var pathSegment = i >= RoutePattern.PathSegments.Count ? null : RoutePattern.PathSegments[i];
if (pathSegment == null && stringSegment.Length > 0)
{
// If pathSegment is null, then we're out of route segments. All we can match is the empty
// string.
return false;
}
else if (pathSegment.IsSimple && pathSegment.Parts[0] is RoutePatternParameterPart parameter && parameter.IsCatchAll)
{
// Nothing to validate for a catch-all - it can match any string, including the empty string.
//
// Also, a catch-all has to be the last part, so we're done.
break;
}
if (!TryMatchLiterals(i++, stringSegment, pathSegment))
{
return false;
}
}
for (; i < RoutePattern.PathSegments.Count; i++)
{
// We've matched the request path so far, but still have remaining route segments. These need
// to be all single-part parameter segments with default values or else they won't match.
var pathSegment = RoutePattern.PathSegments[i];
Debug.Assert(pathSegment != null);
if (!pathSegment.IsSimple)
{
// If the segment is a complex segment, it MUST contain literals, and we've parsed the full
// path so far, so it can't match.
return false;
}
var part = pathSegment.Parts[0];
if (part.IsLiteral || part.IsSeparator)
{
// If the segment is a simple literal - which need the URL to provide a value, so we don't match.
return false;
}
var parameter = (RoutePatternParameterPart)part;
if (parameter.IsCatchAll)
{
// Nothing to validate for a catch-all - it can match any string, including the empty string.
//
// Also, a catch-all has to be the last part, so we're done.
break;
}
// If we get here, this is a simple segment with a parameter. We need it to be optional, or for the
// defaults to have a value.
if (!_hasDefaultValue[i] && !parameter.IsOptional)
{
// There's no default for this (non-optional) parameter so it can't match.
return false;
}
}
// At this point we've very likely got a match, so start capturing values for real.
i = 0;
foreach (var requestSegment in pathTokenizer)
{
var pathSegment = RoutePattern.PathSegments[i++];
if (SavePathSegmentsAsValues(i, values, requestSegment, pathSegment))
{
break;
}
if (!pathSegment.IsSimple)
{
if (!MatchComplexSegment(pathSegment, requestSegment.AsSpan(), values))
{
return false;
}
}
}
for (; i < RoutePattern.PathSegments.Count; i++)
{
// We've matched the request path so far, but still have remaining route segments. We already know these
// are simple parameters that either have a default, or don't need to produce a value.
var pathSegment = RoutePattern.PathSegments[i];
Debug.Assert(pathSegment != null);
Debug.Assert(pathSegment.IsSimple);
var part = pathSegment.Parts[0];
Debug.Assert(part.IsParameter);
// It's ok for a catch-all to produce a null value
if (part is RoutePatternParameterPart parameter && (parameter.IsCatchAll || _hasDefaultValue[i]))
{
// Don't replace an existing value with a null.
var defaultValue = _defaultValues[i];
if (defaultValue != null || !values.ContainsKey(parameter.Name))
{
values[parameter.Name] = defaultValue;
}
}
}
// Copy all remaining default values to the route data
foreach (var kvp in Defaults)
{
#if RVD_TryAdd
values.TryAdd(kvp.Key, kvp.Value);
#else
if (!values.ContainsKey(kvp.Key))
{
values.Add(kvp.Key, kvp.Value);
}
#endif
}
return true;
}
private bool TryMatchLiterals(int index, StringSegment stringSegment, RoutePatternPathSegment pathSegment)
{
if (pathSegment.IsSimple && !pathSegment.Parts[0].IsParameter)
{
// This is a literal segment, so we need to match the text, or the route isn't a match.
if (pathSegment.Parts[0].IsLiteral)
{
var part = (RoutePatternLiteralPart)pathSegment.Parts[0];
if (!stringSegment.Equals(part.Content, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
else
{
var part = (RoutePatternSeparatorPart)pathSegment.Parts[0];
if (!stringSegment.Equals(part.Content, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
}
else if (pathSegment.IsSimple && pathSegment.Parts[0].IsParameter)
{
// For a parameter, validate that it's a has some length, or we have a default, or it's optional.
var part = (RoutePatternParameterPart)pathSegment.Parts[0];
if (stringSegment.Length == 0 &&
!_hasDefaultValue[index] &&
!part.IsOptional)
{
// There's no value for this parameter, the route can't match.
return false;
}
}
else
{
Debug.Assert(!pathSegment.IsSimple);
// Don't attempt to validate a complex segment at this point other than being non-empty,
// do it in the second pass.
}
return true;
}
private bool SavePathSegmentsAsValues(int index, RouteValueDictionary values, StringSegment requestSegment, RoutePatternPathSegment pathSegment)
{
if (pathSegment.IsSimple && pathSegment.Parts[0] is RoutePatternParameterPart parameter && parameter.IsCatchAll)
{
// A catch-all captures til the end of the string.
var captured = requestSegment.Buffer.Substring(requestSegment.Offset);
if (captured.Length > 0)
{
values[parameter.Name] = captured;
}
else
{
// It's ok for a catch-all to produce a null value, so we don't check _hasDefaultValue.
values[parameter.Name] = _defaultValues[index];
}
// A catch-all has to be the last part, so we're done.
return true;
}
else if (pathSegment.IsSimple && pathSegment.Parts[0].IsParameter)
{
// A simple parameter captures the whole segment, or a default value if nothing was
// provided.
parameter = (RoutePatternParameterPart)pathSegment.Parts[0];
if (requestSegment.Length > 0)
{
values[parameter.Name] = requestSegment.ToString();
}
else
{
if (_hasDefaultValue[index])
{
values[parameter.Name] = _defaultValues[index];
}
}
}
return false;
}
internal static bool MatchComplexSegment(
RoutePatternPathSegment routeSegment,
ReadOnlySpan<char> requestSegment,
RouteValueDictionary values)
{
var indexOfLastSegment = routeSegment.Parts.Count - 1;
// We match the request to the template starting at the rightmost parameter
// If the last segment of template is optional, then request can match the
// template with or without the last parameter. So we start with regular matching,
// but if it doesn't match, we start with next to last parameter. Example:
// Template: {p1}/{p2}.{p3?}. If the request is one/two.three it will match right away
// giving p3 value of three. But if the request is one/two, we start matching from the
// rightmost giving p3 the value of two, then we end up not matching the segment.
// In this case we start again from p2 to match the request and we succeed giving
// the value two to p2
if (routeSegment.Parts[indexOfLastSegment] is RoutePatternParameterPart parameter && parameter.IsOptional &&
routeSegment.Parts[indexOfLastSegment - 1].IsSeparator)
{
if (MatchComplexSegmentCore(routeSegment, requestSegment, values, indexOfLastSegment))
{
return true;
}
else
{
var separator = (RoutePatternSeparatorPart)routeSegment.Parts[indexOfLastSegment - 1];
if (requestSegment.EndsWith(
separator.Content,
StringComparison.OrdinalIgnoreCase))
return false;
return MatchComplexSegmentCore(
routeSegment,
requestSegment,
values,
indexOfLastSegment - 2);
}
}
else
{
return MatchComplexSegmentCore(routeSegment, requestSegment, values, indexOfLastSegment);
}
}
private static bool MatchComplexSegmentCore(
RoutePatternPathSegment routeSegment,
ReadOnlySpan<char> requestSegment,
RouteValueDictionary values,
int indexOfLastSegmentUsed)
{
Debug.Assert(routeSegment != null);
Debug.Assert(routeSegment.Parts.Count > 1);
// Find last literal segment and get its last index in the string
var lastIndex = requestSegment.Length;
RoutePatternParameterPart parameterNeedsValue = null; // Keeps track of a parameter segment that is pending a value
RoutePatternPart lastLiteral = null; // Keeps track of the left-most literal we've encountered
var outValues = new RouteValueDictionary();
while (indexOfLastSegmentUsed >= 0)
{
var newLastIndex = lastIndex;
var part = routeSegment.Parts[indexOfLastSegmentUsed];
if (part.IsParameter)
{
// Hold on to the parameter so that we can fill it in when we locate the next literal
parameterNeedsValue = (RoutePatternParameterPart)part;
}
else
{
Debug.Assert(part.IsLiteral || part.IsSeparator);
lastLiteral = part;
var startIndex = lastIndex;
// If we have a pending parameter subsegment, we must leave at least one character for that
if (parameterNeedsValue != null)
{
startIndex--;
}
if (startIndex == 0)
{
return false;
}
int indexOfLiteral;
if (part.IsLiteral)
{
var literal = (RoutePatternLiteralPart)part;
indexOfLiteral = requestSegment.Slice(0, startIndex).LastIndexOf(
literal.Content,
StringComparison.OrdinalIgnoreCase);
}
else
{
var literal = (RoutePatternSeparatorPart)part;
indexOfLiteral = requestSegment.Slice(0, startIndex).LastIndexOf(
literal.Content,
StringComparison.OrdinalIgnoreCase);
}
if (indexOfLiteral == -1)
{
// If we couldn't find this literal index, this segment cannot match
return false;
}
// If the first subsegment is a literal, it must match at the right-most extent of the request URI.
// Without this check if your route had "/Foo/" we'd match the request URI "/somethingFoo/".
// This check is related to the check we do at the very end of this function.
if (indexOfLastSegmentUsed == (routeSegment.Parts.Count - 1))
{
if (part is RoutePatternLiteralPart literal && ((indexOfLiteral + literal.Content.Length) != requestSegment.Length))
{
return false;
}
else if (part is RoutePatternSeparatorPart separator && ((indexOfLiteral + separator.Content.Length) != requestSegment.Length))
{
return false;
}
}
newLastIndex = indexOfLiteral;
}
if ((parameterNeedsValue != null) &&
(((lastLiteral != null) && !part.IsParameter) || (indexOfLastSegmentUsed == 0)))
{
// If we have a pending parameter that needs a value, grab that value
int parameterStartIndex;
int parameterTextLength;
if (lastLiteral == null)
{
if (indexOfLastSegmentUsed == 0)
{
parameterStartIndex = 0;
}
else
{
parameterStartIndex = newLastIndex;
Debug.Assert(false, "indexOfLastSegementUsed should always be 0 from the check above");
}
parameterTextLength = lastIndex;
}
else
{
// If we're getting a value for a parameter that is somewhere in the middle of the segment
if ((indexOfLastSegmentUsed == 0) && (part.IsParameter))
{
parameterStartIndex = 0;
parameterTextLength = lastIndex;
}
else
{
if (lastLiteral.IsLiteral)
{
var literal = (RoutePatternLiteralPart)lastLiteral;
parameterStartIndex = newLastIndex + literal.Content.Length;
}
else
{
var separator = (RoutePatternSeparatorPart)lastLiteral;
parameterStartIndex = newLastIndex + separator.Content.Length;
}
parameterTextLength = lastIndex - parameterStartIndex;
}
}
var parameterValueSpan = requestSegment.Slice(parameterStartIndex, parameterTextLength);
if (parameterValueSpan.Length == 0)
{
// If we're here that means we have a segment that contains multiple sub-segments.
// For these segments all parameters must have non-empty values. If the parameter
// has an empty value it's not a match.
return false;
}
else
{
// If there's a value in the segment for this parameter, use the subsegment value
outValues.Add(parameterNeedsValue.Name, new string(parameterValueSpan));
}
parameterNeedsValue = null;
lastLiteral = null;
}
lastIndex = newLastIndex;
indexOfLastSegmentUsed--;
}
// If the last subsegment is a parameter, it's OK that we didn't parse all the way to the left extent of
// the string since the parameter will have consumed all the remaining text anyway. If the last subsegment
// is a literal then we *must* have consumed the entire text in that literal. Otherwise we end up matching
// the route "Foo" to the request URI "somethingFoo". Thus we have to check that we parsed the *entire*
// request URI in order for it to be a match.
// This check is related to the check we do earlier in this function for LiteralSubsegments.
if (lastIndex == 0 || routeSegment.Parts[0].IsParameter)
{
foreach (var item in outValues)
{
values[item.Key] = item.Value;
}
return true;
}
return false;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using Foundation;
using UIKit;
using SizeF = CoreGraphics.CGSize;
namespace Xamarin.Forms.Platform.iOS
{
public class ButtonRenderer : ViewRenderer<Button, UIButton>
{
UIColor _buttonTextColorDefaultDisabled;
UIColor _buttonTextColorDefaultHighlighted;
UIColor _buttonTextColorDefaultNormal;
bool _titleChanged;
SizeF _titleSize;
// This looks like it should be a const under iOS Classic,
// but that doesn't work under iOS
// ReSharper disable once BuiltInTypeReferenceStyle
// Under iOS Classic Resharper wants to suggest this use the built-in type ref
// but under iOS that suggestion won't work
readonly nfloat _minimumButtonHeight = 44; // Apple docs
public override SizeF SizeThatFits(SizeF size)
{
var result = base.SizeThatFits(size);
if (result.Height < _minimumButtonHeight)
{
result.Height = _minimumButtonHeight;
}
return result;
}
protected override void Dispose(bool disposing)
{
if (Control != null)
Control.TouchUpInside -= OnButtonTouchUpInside;
base.Dispose(disposing);
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Control == null)
{
SetNativeControl(new UIButton(UIButtonType.RoundedRect));
Debug.Assert(Control != null, "Control != null");
_buttonTextColorDefaultNormal = Control.TitleColor(UIControlState.Normal);
_buttonTextColorDefaultHighlighted = Control.TitleColor(UIControlState.Highlighted);
_buttonTextColorDefaultDisabled = Control.TitleColor(UIControlState.Disabled);
Control.TouchUpInside += OnButtonTouchUpInside;
}
UpdateText();
UpdateFont();
UpdateBorder();
UpdateImage();
UpdateTextColor();
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Button.TextProperty.PropertyName)
UpdateText();
else if (e.PropertyName == Button.TextColorProperty.PropertyName)
UpdateTextColor();
else if (e.PropertyName == Button.FontProperty.PropertyName)
UpdateFont();
else if (e.PropertyName == Button.BorderWidthProperty.PropertyName || e.PropertyName == Button.BorderRadiusProperty.PropertyName || e.PropertyName == Button.BorderColorProperty.PropertyName)
UpdateBorder();
else if (e.PropertyName == Button.ImageProperty.PropertyName)
UpdateImage();
}
void OnButtonTouchUpInside(object sender, EventArgs eventArgs)
{
((IButtonController)Element)?.SendClicked();
}
void UpdateBorder()
{
var uiButton = Control;
var button = Element;
if (button.BorderColor != Color.Default)
uiButton.Layer.BorderColor = button.BorderColor.ToCGColor();
uiButton.Layer.BorderWidth = Math.Max(0f, (float)button.BorderWidth);
uiButton.Layer.CornerRadius = button.BorderRadius;
}
void UpdateFont()
{
Control.TitleLabel.Font = Element.ToUIFont();
}
async void UpdateImage()
{
IImageSourceHandler handler;
FileImageSource source = Element.Image;
if (source != null && (handler = Registrar.Registered.GetHandler<IImageSourceHandler>(source.GetType())) != null)
{
UIImage uiimage;
try
{
uiimage = await handler.LoadImageAsync(source, scale: (float)UIScreen.MainScreen.Scale);
}
catch (OperationCanceledException)
{
uiimage = null;
}
UIButton button = Control;
if (button != null && uiimage != null)
{
button.SetImage(uiimage.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), UIControlState.Normal);
button.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
ComputeEdgeInsets(Control, Element.ContentLayout);
}
}
else
{
Control.SetImage(null, UIControlState.Normal);
ClearEdgeInsets(Control);
}
((IVisualElementController)Element).NativeSizeChanged();
}
void UpdateText()
{
var newText = Element.Text;
if (Control.Title(UIControlState.Normal) != newText)
{
Control.SetTitle(Element.Text, UIControlState.Normal);
_titleChanged = true;
}
}
void UpdateTextColor()
{
if (Element.TextColor == Color.Default)
{
Control.SetTitleColor(_buttonTextColorDefaultNormal, UIControlState.Normal);
Control.SetTitleColor(_buttonTextColorDefaultHighlighted, UIControlState.Highlighted);
Control.SetTitleColor(_buttonTextColorDefaultDisabled, UIControlState.Disabled);
}
else
{
Control.SetTitleColor(Element.TextColor.ToUIColor(), UIControlState.Normal);
Control.SetTitleColor(Element.TextColor.ToUIColor(), UIControlState.Highlighted);
Control.SetTitleColor(_buttonTextColorDefaultDisabled, UIControlState.Disabled);
Control.TintColor = Element.TextColor.ToUIColor();
}
}
void ClearEdgeInsets(UIButton button)
{
if (button == null)
{
return;
}
Control.ImageEdgeInsets = new UIEdgeInsets(0, 0, 0, 0);
Control.TitleEdgeInsets = new UIEdgeInsets(0, 0, 0, 0);
Control.ContentEdgeInsets = new UIEdgeInsets(0, 0, 0, 0);
}
void ComputeEdgeInsets(UIButton button, Button.ButtonContentLayout layout)
{
if (button?.ImageView?.Image == null || string.IsNullOrEmpty(button.TitleLabel?.Text))
{
return;
}
var position = layout.Position;
var spacing = (nfloat)(layout.Spacing / 2);
if (position == Button.ButtonContentLayout.ImagePosition.Left)
{
button.ImageEdgeInsets = new UIEdgeInsets(0, -spacing, 0, spacing);
button.TitleEdgeInsets = new UIEdgeInsets(0, spacing, 0, -spacing);
button.ContentEdgeInsets = new UIEdgeInsets(0, 2 * spacing, 0, 2 * spacing);
return;
}
if (_titleChanged)
{
var stringToMeasure = new NSString(button.TitleLabel.Text);
UIStringAttributes attribs = new UIStringAttributes { Font = button.TitleLabel.Font };
_titleSize = stringToMeasure.GetSizeUsingAttributes(attribs);
_titleChanged = false;
}
var labelWidth = _titleSize.Width;
var imageWidth = button.ImageView.Image.Size.Width;
if (position == Button.ButtonContentLayout.ImagePosition.Right)
{
button.ImageEdgeInsets = new UIEdgeInsets(0, labelWidth + spacing, 0, -labelWidth - spacing);
button.TitleEdgeInsets = new UIEdgeInsets(0, -imageWidth - spacing, 0, imageWidth + spacing);
button.ContentEdgeInsets = new UIEdgeInsets(0, 2 * spacing, 0, 2 * spacing);
return;
}
var imageVertOffset = (_titleSize.Height / 2);
var titleVertOffset = (button.ImageView.Image.Size.Height / 2);
var edgeOffset = (float)Math.Min(imageVertOffset, titleVertOffset);
button.ContentEdgeInsets = new UIEdgeInsets(edgeOffset, 0, edgeOffset, 0);
var horizontalImageOffset = labelWidth / 2;
var horizontalTitleOffset = imageWidth / 2;
if (position == Button.ButtonContentLayout.ImagePosition.Bottom)
{
imageVertOffset = -imageVertOffset;
titleVertOffset = -titleVertOffset;
}
button.ImageEdgeInsets = new UIEdgeInsets(-imageVertOffset, horizontalImageOffset, imageVertOffset, -horizontalImageOffset);
button.TitleEdgeInsets = new UIEdgeInsets(titleVertOffset, -horizontalTitleOffset, -titleVertOffset, horizontalTitleOffset);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class HttpClientHandler_ServerCertificates_Test
{
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_ValidCertificate_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public void UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
var handler = new HttpClientHandler();
handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null);
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.PostAsync(
Configuration.Http.SecureRemoteEchoServer,
new StringContent("This is a test"));
Task.WaitAll(proxyTask, responseTask);
using (responseTask.Result)
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
Configuration.Http.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:Configuration.Http.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
Assert.Equal(SslPolicyErrors.None, errors);
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagates()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
Assert.Same(e, await Assert.ThrowsAsync<DivideByZeroException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)));
}
}
public static readonly object[][] CertificateValidationServers =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer },
new object[] { Configuration.Http.SelfSignedCertRemoteServer },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer));
}
}
public static readonly object[][] CertificateValidationServersAndExpectedPolicies =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(7812, TestPlatforms.Windows)]
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
Assert.Equal(expectedErrors, errors);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
private static bool BackendSupportsCustomCertificateHandling =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ||
(CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false);
private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
[DllImport("System.Net.Http.Native", EntryPoint = "HttpNative_GetSslVersionDescription")]
private static extern string CurlSslVersionDescription();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using CURLcode = Interop.Http.CURLcode;
using CURLINFO = Interop.Http.CURLINFO;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private static class SslProvider
{
private static readonly Interop.Http.SslCtxCallback s_sslCtxCallback = SslCtxCallback;
private static readonly Interop.Ssl.AppVerifyCallback s_sslVerifyCallback = VerifyCertChain;
internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
{
Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual);
// Create a client certificate provider if client certs may be used.
X509Certificate2Collection clientCertificates = easy._handler._clientCertificates;
ClientCertificateProvider certProvider =
clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic
clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs
null; // manual without certs
IntPtr userPointer = IntPtr.Zero;
if (certProvider != null)
{
// The client cert provider needs to be passed through to the callback, and thus
// we create a GCHandle to keep it rooted. This handle needs to be cleaned up
// when the request has completed, and a simple and pay-for-play way to do that
// is by cleaning it up in a continuation off of the request.
userPointer = GCHandle.ToIntPtr(certProvider._gcHandle);
easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider,
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
// Register the callback with libcurl. We need to register even if there's no user-provided
// server callback and even if there are no client certificates, because we support verifying
// server certificates against more than those known to OpenSSL.
CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer);
switch (answer)
{
case CURLcode.CURLE_OK:
// We successfully registered. If we'll be invoking a user-provided callback to verify the server
// certificate as part of that, disable libcurl's verification of the host name. The user's callback
// needs to be given the opportunity to examine the cert, and our logic will determine whether
// the host name matches and will inform the callback of that.
if (easy._handler.ServerCertificateValidationCallback != null)
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); // don't verify the peer cert's hostname
// We don't change the SSL_VERIFYPEER setting, as setting it to 0 will cause
// SSL and libcurl to ignore the result of the server callback.
}
// The allowed SSL protocols will be set in the configuration callback.
break;
case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior
case CURLcode.CURLE_NOT_BUILT_IN: // Curl 7.39 and later
// It's ok if we failed to register the callback if all of the defaults are in play
// with relation to handling of certificates. But if that's not the case, failing to
// register the callback will result in those options not being factored in, which is
// a significant enough error that we need to fail.
EventSourceTrace("CURLOPT_SSL_CTX_FUNCTION not supported: {0}", answer);
if (certProvider != null ||
easy._handler.ServerCertificateValidationCallback != null ||
easy._handler.CheckCertificateRevocationList)
{
throw new PlatformNotSupportedException(
SR.Format(SR.net_http_unix_invalid_certcallback_option, CurlVersionDescription, CurlSslVersionDescription));
}
// Since there won't be a callback to configure the allowed SSL protocols, configure them here.
SetSslVersion(easy);
break;
default:
ThrowIfCURLEError(answer);
break;
}
}
private static void SetSslVersion(EasyRequest easy, IntPtr sslCtx = default(IntPtr))
{
// Get the requested protocols.
System.Security.Authentication.SslProtocols protocols = easy._handler.ActualSslProtocols;
// We explicitly disallow choosing SSL2/3. Make sure they were filtered out.
Debug.Assert((protocols & ~SecurityProtocol.AllowedSecurityProtocols) == 0,
"Disallowed protocols should have been filtered out.");
// libcurl supports options for either enabling all of the TLS1.* protocols or enabling
// just one of them; it doesn't currently support enabling two of the three, e.g. you can't
// pick TLS1.1 and TLS1.2 but not TLS1.0, but you can select just TLS1.2.
Interop.Http.CurlSslVersion curlSslVersion;
switch (protocols)
{
case System.Security.Authentication.SslProtocols.Tls:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_0;
break;
case System.Security.Authentication.SslProtocols.Tls11:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_1;
break;
case System.Security.Authentication.SslProtocols.Tls12:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_2;
break;
case System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1;
break;
default:
throw new NotSupportedException(SR.net_securityprotocolnotsupported);
}
try
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)curlSslVersion);
}
catch (CurlException e) when (e.HResult == (int)CURLcode.CURLE_UNKNOWN_OPTION)
{
throw new NotSupportedException(SR.net_securityprotocolnotsupported, e);
}
}
private static CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer)
{
// Configure the SSL protocols allowed.
EasyRequest easy;
if (!TryGetEasyRequest(curl, out easy))
{
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
Interop.Ssl.SetProtocolOptions(sslCtx, easy._handler.ActualSslProtocols);
// Configure the SSL server certificate verification callback.
Interop.Ssl.SslCtxSetCertVerifyCallback(sslCtx, s_sslVerifyCallback, curl);
// If a client certificate provider was provided, also configure the client certificate callback.
if (userPointer != IntPtr.Zero)
{
try
{
// Provider is passed in via a GCHandle. Get the provider, which contains
// the client certificate callback delegate.
GCHandle handle = GCHandle.FromIntPtr(userPointer);
ClientCertificateProvider provider = (ClientCertificateProvider)handle.Target;
if (provider == null)
{
Debug.Fail($"Expected non-null provider in {nameof(SslCtxCallback)}");
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
// Register the callback.
Interop.Ssl.SslCtxSetClientCertCallback(sslCtx, provider._callback);
EventSourceTrace("Registered client certificate callback.");
}
catch (Exception e)
{
Debug.Fail($"Exception in {nameof(SslCtxCallback)}", e.ToString());
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
}
return CURLcode.CURLE_OK;
}
private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy)
{
Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null");
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
if (getInfoResult == CURLcode.CURLE_OK)
{
return MultiAgent.TryGetEasyRequestFromGCHandle(gcHandlePtr, out easy);
}
Debug.Fail($"Failed to get info on a completing easy handle: {getInfoResult}");
easy = null;
return false;
}
private static int VerifyCertChain(IntPtr storeCtxPtr, IntPtr curlPtr)
{
EasyRequest easy;
if (!TryGetEasyRequest(curlPtr, out easy))
{
EventSourceTrace("Could not find associated easy request: {0}", curlPtr);
return 0;
}
using (var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false))
{
IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx);
if (IntPtr.Zero == leafCertPtr)
{
EventSourceTrace("Invalid certificate pointer");
return 0;
}
using (X509Certificate2 leafCert = new X509Certificate2(leafCertPtr))
{
// Set up the CBT with this certificate.
easy._requestContentStream?.SetChannelBindingToken(leafCert);
// We need to respect the user's server validation callback if there is one. If there isn't one,
// we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled,
// as OpenSSL doesn't do that.
if (easy._handler.ServerCertificateValidationCallback == null &&
!easy._handler.CheckCertificateRevocationList)
{
// Start by using the default verification provided directly by OpenSSL.
// If it succeeds in verifying the cert chain, we're done. Employing this instead of
// our custom implementation will need to be revisited if we ever decide to introduce a
// "disallowed" store that enables users to "untrust" certs the system trusts.
int sslResult = Interop.Crypto.X509VerifyCert(storeCtx);
if (sslResult == 1)
{
return 1;
}
// X509_verify_cert can return < 0 in the case of programmer error
Debug.Assert(sslResult == 0, "Unexpected error from X509_verify_cert: " + sslResult);
}
// Either OpenSSL verification failed, or there was a server validation callback.
// Either way, fall back to manual and more expensive verification that includes
// checking the user's certs (not just the system store ones as OpenSSL does).
X509Certificate2[] otherCerts;
int otherCertsCount = 0;
bool success;
using (X509Chain chain = new X509Chain())
{
chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx))
{
if (extraStack.IsInvalid)
{
otherCerts = Array.Empty<X509Certificate2>();
}
else
{
int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack);
otherCerts = new X509Certificate2[extraSize];
for (int i = 0; i < extraSize; i++)
{
IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i);
if (certPtr != IntPtr.Zero)
{
X509Certificate2 cert = new X509Certificate2(certPtr);
otherCerts[otherCertsCount++] = cert;
chain.ChainPolicy.ExtraStore.Add(cert);
}
}
}
}
var serverCallback = easy._handler._serverCertificateValidationCallback;
if (serverCallback == null)
{
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: false, hostName: null); // libcurl already verifies the host name
success = errors == SslPolicyErrors.None;
}
else
{
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here
try
{
success = serverCallback(easy._requestMessage, leafCert, chain, errors);
}
catch (Exception exc)
{
EventSourceTrace("Server validation callback threw exception: {0}", exc);
easy.FailRequest(exc);
success = false;
}
}
}
for (int i = 0; i < otherCertsCount; i++)
{
otherCerts[i].Dispose();
}
return success ? 1 : 0;
}
}
}
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Orleans.Runtime
{
internal abstract class TaskSchedulerAgent : IDisposable
{
public enum FaultBehavior
{
CrashOnFault, // Crash the process if the agent faults
RestartOnFault, // Restart the agent if it faults
IgnoreFault // Allow the agent to stop if it faults, but take no other action (other than logging)
}
public enum AgentState
{
Stopped,
Running,
StopRequested
}
protected CancellationTokenSource Cts;
protected object Lockable;
protected ILogger Log;
protected ILoggerFactory loggerFactory;
protected readonly string type;
protected FaultBehavior OnFault;
protected bool disposed;
public AgentState State { get; private set; }
internal string Name { get; private set; }
protected TaskSchedulerAgent(string nameSuffix, ILoggerFactory loggerFactory)
{
Cts = new CancellationTokenSource();
var thisType = GetType();
type = thisType.Namespace + "." + thisType.Name;
if (type.StartsWith("Orleans.", StringComparison.Ordinal))
{
type = type.Substring(8);
}
if (!string.IsNullOrEmpty(nameSuffix))
{
Name = type + "/" + nameSuffix;
}
else
{
Name = type;
}
Lockable = new object();
OnFault = FaultBehavior.IgnoreFault;
this.loggerFactory = loggerFactory;
this.Log = loggerFactory.CreateLogger(Name);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
try
{
if (State != AgentState.Stopped)
{
Stop();
}
}
catch (Exception exc)
{
// ignore. Just make sure DomainUnload handler does not throw.
Log.Debug("Ignoring error during Stop: {0}", exc);
}
}
public virtual void Start()
{
ThrowIfDisposed();
lock (Lockable)
{
if (State == AgentState.Running)
{
return;
}
if (State == AgentState.Stopped)
{
Cts = new CancellationTokenSource();
}
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
LogStatus(Log, "Starting AsyncAgent {0} on managed thread {1}", Name, Thread.CurrentThread.ManagedThreadId);
State = AgentState.Running;
}
Task.Run(() => this.StartAsync()).Ignore();
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Started asynch agent " + this.Name);
}
private async Task StartAsync()
{
var handled = false;
try
{
await this.Run();
}
catch (Exception exception)
{
this.HandleFault(exception);
handled = true;
}
finally
{
if (!handled)
{
if (this.OnFault == FaultBehavior.RestartOnFault && !this.Cts.IsCancellationRequested)
{
try
{
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Run completed on agent " + this.Name + " - restarting");
this.Start();
}
catch (Exception exc)
{
this.Log.Error(ErrorCode.Runtime_Error_100027, "Unable to restart AsynchAgent", exc);
this.State = AgentState.Stopped;
}
}
}
}
}
protected abstract Task Run();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public virtual void Stop()
{
try
{
ThrowIfDisposed();
lock (Lockable)
{
if (State == AgentState.Running)
{
State = AgentState.StopRequested;
Cts.Cancel();
State = AgentState.Stopped;
}
}
AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
}
catch (Exception exc)
{
// ignore. Just make sure stop does not throw.
Log.Debug("Ignoring error during Stop: {0}", exc);
}
Log.Debug("Stopped agent");
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing || disposed) return;
if (Cts != null)
{
Cts.Dispose();
Cts = null;
}
disposed = true;
}
public override string ToString()
{
return Name;
}
internal static bool IsStarting { get; set; }
/// <summary>
/// Handles fault
/// </summary>
/// <param name="ex"></param>
/// <returns>false agent has been stopped</returns>
protected bool HandleFault(Exception ex)
{
if (State == AgentState.StopRequested)
{
return false;
}
else
{
State = AgentState.Stopped;
}
if (ex is ThreadAbortException)
{
return false;
}
LogExecutorError(ex);
if (OnFault == FaultBehavior.RestartOnFault && !Cts.IsCancellationRequested)
{
try
{
Start();
}
catch (Exception exc)
{
Log.Error(ErrorCode.Runtime_Error_100027, "Unable to restart AsynchAgent", exc);
State = AgentState.Stopped;
}
}
return State != AgentState.Stopped;
}
private void LogExecutorError(Exception exc)
{
var logMessagePrefix = $"Asynch agent {Name} encountered unexpected exception";
switch (OnFault)
{
case FaultBehavior.CrashOnFault:
var logMessage = $"{logMessagePrefix} The process will be terminated.";
Console.WriteLine(logMessage, exc);
Log.Error(ErrorCode.Runtime_Error_100023, logMessage, exc);
Log.Fail(ErrorCode.Runtime_Error_100024, logMessage);
break;
case FaultBehavior.IgnoreFault:
Log.Error(ErrorCode.Runtime_Error_100025, $"{logMessagePrefix} The executor will exit.", exc);
break;
case FaultBehavior.RestartOnFault:
Log.Error(ErrorCode.Runtime_Error_100026, $"{logMessagePrefix} The Stage will be restarted.", exc);
break;
default:
throw new NotImplementedException();
}
}
private static void LogStatus(ILogger log, string msg, params object[] args)
{
if (IsStarting)
{
// Reduce log noise during silo startup
if (log.IsEnabled(LogLevel.Debug)) log.Debug(msg, args);
}
else
{
// Changes in agent threads during all operations aside for initial creation are usually important diag events.
log.Info(msg, args);
}
}
private void ThrowIfDisposed()
{
if (disposed)
{
throw new ObjectDisposedException("Cannot access disposed AsynchAgent");
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security.Google.Infrastructure;
using Microsoft.Owin.Security.Infrastructure;
namespace Microsoft.Owin.Security.Google
{
internal class GoogleAuthenticationHandler : AuthenticationHandler<GoogleAuthenticationOptions>
{
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
public GoogleAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
_httpClient = httpClient;
_logger = logger;
}
public override async Task<bool> InvokeAsync()
{
if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
{
return await InvokeReturnPathAsync();
}
return false;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
IReadableStringCollection query = Request.Query;
properties = UnpackStateParameter(query);
if (properties == null)
{
_logger.WriteWarning("Invalid return state");
return null;
}
// Anti-CSRF
if (!ValidateCorrelationId(properties, _logger))
{
return new AuthenticationTicket(null, properties);
}
Message message = await ParseRequestMessageAsync(query);
bool messageValidated = false;
Property mode;
if (!message.Properties.TryGetValue("mode.http://specs.openid.net/auth/2.0", out mode))
{
_logger.WriteWarning("Missing mode parameter");
return new AuthenticationTicket(null, properties);
}
if (string.Equals("cancel", mode.Value, StringComparison.Ordinal))
{
_logger.WriteWarning("User cancelled signin request");
return new AuthenticationTicket(null, properties);
}
if (string.Equals("id_res", mode.Value, StringComparison.Ordinal))
{
mode.Value = "check_authentication";
var requestBody = new FormUrlEncodedContent(message.ToFormValues());
HttpResponseMessage response = await _httpClient.PostAsync("https://www.google.com/accounts/o8/ud", requestBody, Request.CallCancelled);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var verifyBody = new Dictionary<string, string[]>();
foreach (var line in responseBody.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
int delimiter = line.IndexOf(':');
if (delimiter != -1)
{
verifyBody.Add("openid." + line.Substring(0, delimiter), new[] { line.Substring(delimiter + 1) });
}
}
var verifyMessage = new Message(new ReadableStringCollection(verifyBody), strict: false);
Property isValid;
if (verifyMessage.Properties.TryGetValue("is_valid.http://specs.openid.net/auth/2.0", out isValid))
{
if (string.Equals("true", isValid.Value, StringComparison.Ordinal))
{
messageValidated = true;
}
else
{
messageValidated = false;
}
}
}
// http://openid.net/specs/openid-authentication-2_0.html#verify_return_to
// To verify that the "openid.return_to" URL matches the URL that is processing this assertion:
// * The URL scheme, authority, and path MUST be the same between the two URLs.
// * Any query parameters that are present in the "openid.return_to" URL MUST also
// be present with the same values in the URL of the HTTP request the RP received.
if (messageValidated)
{
// locate the required return_to parameter
string actualReturnTo;
if (!message.TryGetValue("return_to.http://specs.openid.net/auth/2.0", out actualReturnTo))
{
_logger.WriteWarning("openid.return_to parameter missing at return address");
messageValidated = false;
}
else
{
// create the expected return_to parameter based on the URL that is processing
// the assertion, plus exactly and only the the query string parameter (state)
// that this RP must have received
string expectedReturnTo = BuildReturnTo(GetStateParameter(query));
if (!string.Equals(actualReturnTo, expectedReturnTo, StringComparison.Ordinal))
{
_logger.WriteWarning("openid.return_to parameter not equal to expected value based on return address");
messageValidated = false;
}
}
}
if (messageValidated)
{
IDictionary<string, string> attributeExchangeProperties = new Dictionary<string, string>();
foreach (var typeProperty in message.Properties.Values)
{
if (typeProperty.Namespace == "http://openid.net/srv/ax/1.0" &&
typeProperty.Name.StartsWith("type."))
{
string qname = "value." + typeProperty.Name.Substring("type.".Length) + "http://openid.net/srv/ax/1.0";
Property valueProperty;
if (message.Properties.TryGetValue(qname, out valueProperty))
{
attributeExchangeProperties.Add(typeProperty.Value, valueProperty.Value);
}
}
}
var responseNamespaces = new object[]
{
new XAttribute(XNamespace.Xmlns + "openid", "http://specs.openid.net/auth/2.0"),
new XAttribute(XNamespace.Xmlns + "openid.ax", "http://openid.net/srv/ax/1.0")
};
IEnumerable<object> responseProperties = message.Properties
.Where(p => p.Value.Namespace != null)
.Select(p => (object)new XElement(XName.Get(p.Value.Name.Substring(0, p.Value.Name.Length - 1), p.Value.Namespace), p.Value.Value));
var responseMessage = new XElement("response", responseNamespaces.Concat(responseProperties).ToArray());
var identity = new ClaimsIdentity(Options.AuthenticationType);
XElement claimedId = responseMessage.Element(XName.Get("claimed_id", "http://specs.openid.net/auth/2.0"));
if (claimedId != null)
{
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, claimedId.Value, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
string firstValue;
if (attributeExchangeProperties.TryGetValue("http://axschema.org/namePerson/first", out firstValue))
{
identity.AddClaim(new Claim(ClaimTypes.GivenName, firstValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
string lastValue;
if (attributeExchangeProperties.TryGetValue("http://axschema.org/namePerson/last", out lastValue))
{
identity.AddClaim(new Claim(ClaimTypes.Surname, lastValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
string nameValue;
if (attributeExchangeProperties.TryGetValue("http://axschema.org/namePerson", out nameValue))
{
identity.AddClaim(new Claim(ClaimTypes.Name, nameValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
else if (!string.IsNullOrEmpty(firstValue) && !string.IsNullOrEmpty(lastValue))
{
identity.AddClaim(new Claim(ClaimTypes.Name, firstValue + " " + lastValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
else if (!string.IsNullOrEmpty(firstValue))
{
identity.AddClaim(new Claim(ClaimTypes.Name, firstValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
else if (!string.IsNullOrEmpty(lastValue))
{
identity.AddClaim(new Claim(ClaimTypes.Name, lastValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
string emailValue;
if (attributeExchangeProperties.TryGetValue("http://axschema.org/contact/email", out emailValue))
{
identity.AddClaim(new Claim(ClaimTypes.Email, emailValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
var context = new GoogleAuthenticatedContext(
Context,
identity,
properties,
responseMessage,
attributeExchangeProperties);
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
return new AuthenticationTicket(null, properties);
}
catch (Exception ex)
{
_logger.WriteError("Authentication failed", ex);
return new AuthenticationTicket(null, properties);
}
}
private static string GetStateParameter(IReadableStringCollection query)
{
IList<string> values = query.GetValues("state");
if (values != null && values.Count == 1)
{
return values[0];
}
return null;
}
private AuthenticationProperties UnpackStateParameter(IReadableStringCollection query)
{
string state = GetStateParameter(query);
if (state != null)
{
return Options.StateDataFormat.Unprotect(state);
}
return null;
}
private string BuildReturnTo(string state)
{
return Request.Scheme + "://" + Request.Host +
RequestPathBase + Options.CallbackPath +
"?state=" + Uri.EscapeDataString(state);
}
private async Task<Message> ParseRequestMessageAsync(IReadableStringCollection query)
{
if (Request.Method == "POST")
{
IFormCollection form = await Request.ReadFormAsync();
return new Message(form, strict: true);
}
return new Message(query, strict: true);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "MemoryStream.Dispose is idempotent")]
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return Task.FromResult<object>(null);
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge != null)
{
string requestPrefix = Request.Scheme + Uri.SchemeDelimiter + Request.Host;
var state = challenge.Properties;
if (String.IsNullOrEmpty(state.RedirectUri))
{
state.RedirectUri = requestPrefix + Request.PathBase + Request.Path + Request.QueryString;
}
// Anti-CSRF
GenerateCorrelationId(state);
string returnTo = BuildReturnTo(Options.StateDataFormat.Protect(state));
string authorizationEndpoint =
"https://www.google.com/accounts/o8/ud" +
"?openid.ns=" + Uri.EscapeDataString("http://specs.openid.net/auth/2.0") +
"&openid.ns.ax=" + Uri.EscapeDataString("http://openid.net/srv/ax/1.0") +
"&openid.mode=" + Uri.EscapeDataString("checkid_setup") +
"&openid.claimed_id=" + Uri.EscapeDataString("http://specs.openid.net/auth/2.0/identifier_select") +
"&openid.identity=" + Uri.EscapeDataString("http://specs.openid.net/auth/2.0/identifier_select") +
"&openid.return_to=" + Uri.EscapeDataString(returnTo) +
"&openid.realm=" + Uri.EscapeDataString(requestPrefix) +
"&openid.ax.mode=" + Uri.EscapeDataString("fetch_request") +
"&openid.ax.type.email=" + Uri.EscapeDataString("http://axschema.org/contact/email") +
"&openid.ax.type.name=" + Uri.EscapeDataString("http://axschema.org/namePerson") +
"&openid.ax.type.first=" + Uri.EscapeDataString("http://axschema.org/namePerson/first") +
"&openid.ax.type.last=" + Uri.EscapeDataString("http://axschema.org/namePerson/last") +
"&openid.ax.required=" + Uri.EscapeDataString("email,name,first,last");
Response.StatusCode = 302;
Response.Headers.Set("Location", authorizationEndpoint);
}
return Task.FromResult<object>(null);
}
public async Task<bool> InvokeReturnPathAsync()
{
AuthenticationTicket model = await AuthenticateAsync();
if (model == null)
{
_logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new GoogleReturnEndpointContext(Context, model);
context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType;
context.RedirectUri = model.Properties.RedirectUri;
model.Properties.RedirectUri = null;
await Options.Provider.ReturnEndpoint(context);
if (context.SignInAsAuthenticationType != null && context.Identity != null)
{
ClaimsIdentity signInIdentity = context.Identity;
if (!string.Equals(signInIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
{
signInIdentity = new ClaimsIdentity(signInIdentity.Claims, context.SignInAsAuthenticationType, signInIdentity.NameClaimType, signInIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, signInIdentity);
}
if (!context.IsRequestCompleted && context.RedirectUri != null)
{
if (context.Identity == null)
{
// add a redirect hint that sign-in failed in some way
context.RedirectUri = WebUtilities.AddQueryString(context.RedirectUri, "error", "access_denied");
}
Response.Redirect(context.RedirectUri);
context.RequestCompleted();
}
return context.IsRequestCompleted;
}
}
}
| |
using System;
using AutoMapper;
namespace Benchmark.Flattening
{
using System.Collections.Generic;
using System.Linq;
public class DeepTypeMapper : IObjectToObjectMapper
{
private Customer _customer;
private IMapper _mapper;
public string Name { get; } = "Deep Types";
public void Initialize()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Address, Address>();
cfg.CreateMap<Address, AddressDTO>();
cfg.CreateMap<Customer, CustomerDTO>();
});
config.AssertConfigurationIsValid();
_mapper = config.CreateMapper();
_customer = new Customer()
{
Address = new Address() { City = "istanbul", Country = "turkey", Id = 1, Street = "istiklal cad." },
HomeAddress = new Address() { City = "istanbul", Country = "turkey", Id = 2, Street = "istiklal cad." },
Id = 1,
Name = "Eduardo Najera",
Credit = 234.7m,
WorkAddresses = new List<Address>()
{
new Address() {City = "istanbul", Country = "turkey", Id = 5, Street = "istiklal cad."},
new Address() {City = "izmir", Country = "turkey", Id = 6, Street = "konak"}
},
Addresses = new List<Address>()
{
new Address() {City = "istanbul", Country = "turkey", Id = 3, Street = "istiklal cad."},
new Address() {City = "izmir", Country = "turkey", Id = 4, Street = "konak"}
}.ToArray()
};
}
public object Map()
{
return _mapper.Map<Customer, CustomerDTO>(_customer);
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class AddressDTO
{
public int Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public decimal? Credit { get; set; }
public Address Address { get; set; }
public Address HomeAddress { get; set; }
public Address[] Addresses { get; set; }
public List<Address> WorkAddresses { get; set; }
}
public class CustomerDTO
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public AddressDTO HomeAddress { get; set; }
public AddressDTO[] Addresses { get; set; }
public List<AddressDTO> WorkAddresses { get; set; }
public string AddressCity { get; set; }
}
}
public class ManualDeepTypeMapper : IObjectToObjectMapper
{
private Customer _customer;
public string Name { get; } = "Manual Deep Types";
public void Initialize()
{
_customer = new Customer()
{
Address = new Address() { City = "istanbul", Country = "turkey", Id = 1, Street = "istiklal cad." },
HomeAddress = new Address() { City = "istanbul", Country = "turkey", Id = 2, Street = "istiklal cad." },
Id = 1,
Name = "Eduardo Najera",
Credit = 234.7m,
WorkAddresses = new List<Address>()
{
new Address() {City = "istanbul", Country = "turkey", Id = 5, Street = "istiklal cad."},
new Address() {City = "izmir", Country = "turkey", Id = 6, Street = "konak"}
},
Addresses = new List<Address>()
{
new Address() {City = "istanbul", Country = "turkey", Id = 3, Street = "istiklal cad."},
new Address() {City = "izmir", Country = "turkey", Id = 4, Street = "konak"}
}.ToArray()
};
}
public object Map()
{
var dto = new CustomerDTO();
dto.Id = _customer.Id;
dto.Name = _customer.Name;
dto.AddressCity = _customer.Address.City;
dto.Address = new Address() { Id = _customer.Address.Id, Street = _customer.Address.Street, Country = _customer.Address.Country, City = _customer.Address.City };
dto.HomeAddress = new AddressDTO() { Id = _customer.HomeAddress.Id, Country = _customer.HomeAddress.Country, City = _customer.HomeAddress.City };
dto.Addresses = new AddressDTO[_customer.Addresses.Length];
for (int i = 0; i < _customer.Addresses.Length; i++)
{
dto.Addresses[i] = new AddressDTO() { Id = _customer.Addresses[i].Id, Country = _customer.Addresses[i].Country, City = _customer.Addresses[i].City };
}
dto.WorkAddresses = new List<AddressDTO>();
foreach (var workAddress in _customer.WorkAddresses)
{
dto.WorkAddresses.Add(new AddressDTO() { Id = workAddress.Id, Country = workAddress.Country, City = workAddress.City });
}
return dto;
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class AddressDTO
{
public int Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public decimal? Credit { get; set; }
public Address Address { get; set; }
public Address HomeAddress { get; set; }
public Address[] Addresses { get; set; }
public ICollection<Address> WorkAddresses { get; set; }
}
public class CustomerDTO
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public AddressDTO HomeAddress { get; set; }
public AddressDTO[] Addresses { get; set; }
public List<AddressDTO> WorkAddresses { get; set; }
public string AddressCity { get; set; }
}
}
public class ComplexTypeMapper : IObjectToObjectMapper
{
private Foo _foo;
public string Name { get; } = "Complex Types";
private IMapper _mapper;
public void Initialize()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Foo, FooDest>();
cfg.CreateMap<InnerFoo, InnerFooDest>();
});
config.AssertConfigurationIsValid();
_mapper = config.CreateMapper();
_foo = Foo.New();
}
public object Map()
{
var dest = _mapper.Map<Foo, FooDest>(_foo);
return dest;
}
}
public class Foo
{
public static Foo New() => new Foo
{
Name = "foo",
Int32 = 12,
Int64 = 123123,
NullInt = 16,
DateTime = DateTime.Now,
Doublen = 2312112,
Foo1 = new InnerFoo { Name = "foo one" },
Foos = new List<InnerFoo>
{
new InnerFoo {Name = "j1", Int64 = 123, NullInt = 321},
new InnerFoo {Name = "j2", Int32 = 12345, NullInt = 54321},
new InnerFoo {Name = "j3", Int32 = 12345, NullInt = 54321},
},
FooArr = new[]
{
new InnerFoo {Name = "a1"},
new InnerFoo {Name = "a2"},
new InnerFoo {Name = "a3"},
},
IntArr = new[] { 1, 2, 3, 4, 5 },
Ints = new[] { 7, 8, 9 },
};
public string Name { get; set; }
public int Int32 { get; set; }
public long Int64 { set; get; }
public int? NullInt { get; set; }
public float Floatn { get; set; }
public double Doublen { get; set; }
public DateTime DateTime { get; set; }
public InnerFoo Foo1 { get; set; }
public List<InnerFoo> Foos { get; set; }
public InnerFoo[] FooArr { get; set; }
public int[] IntArr { get; set; }
public int[] Ints { get; set; }
}
public class InnerFoo
{
public string Name { get; set; }
public int Int32 { get; set; }
public long Int64 { set; get; }
public int? NullInt { get; set; }
}
public class InnerFooDest
{
public string Name { get; set; }
public int Int32 { get; set; }
public long Int64 { set; get; }
public int? NullInt { get; set; }
}
public class FooDest
{
public string Name { get; set; }
public int Int32 { get; set; }
public long Int64 { set; get; }
public int? NullInt { get; set; }
public float Floatn { get; set; }
public double Doublen { get; set; }
public DateTime DateTime { get; set; }
public InnerFooDest Foo1 { get; set; }
public List<InnerFooDest> Foos { get; set; }
public InnerFooDest[] FooArr { get; set; }
public int[] IntArr { get; set; }
public int[] Ints { get; set; }
}
public class ManualComplexTypeMapper : IObjectToObjectMapper
{
private Foo _foo;
public string Name { get; } = "Manual Complex Types";
public void Initialize()
{
_foo = Foo.New();
}
public object Map()
{
var dest = new FooDest
{
Name = _foo.Name,
Int32 = _foo.Int32,
Int64 = _foo.Int64,
NullInt = _foo.NullInt,
DateTime = _foo.DateTime,
Doublen = _foo.Doublen,
Foo1 = new InnerFooDest { Name = _foo.Foo1.Name },
Foos = new List<InnerFooDest>(_foo.Foos.Count),
FooArr = new InnerFooDest[_foo.Foos.Count],
IntArr = new int[_foo.IntArr.Length],
Ints = _foo.Ints.ToArray(),
};
foreach(var foo in _foo.Foos)
{
dest.Foos.Add(new InnerFooDest { Name = foo.Name, Int64 = foo.Int64, NullInt = foo.NullInt });
}
;
for(int index = 0; index < _foo.Foos.Count; index++)
{
var foo = _foo.Foos[index];
dest.FooArr[index] = new InnerFooDest { Name = foo.Name, Int64 = foo.Int64, NullInt = foo.NullInt };
}
Array.Copy(_foo.IntArr, dest.IntArr, _foo.IntArr.Length);
return dest;
}
}
public class CtorMapper : IObjectToObjectMapper
{
private Model11 _model;
public string Name => "CtorMapper";
private IMapper _mapper;
public void Initialize()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Model11, Dto11>());
config.AssertConfigurationIsValid();
_mapper = config.CreateMapper();
_model = new Model11 { Value = 5 };
}
public object Map()
{
return _mapper.Map<Model11, Dto11>(_model);
}
}
public class ManualCtorMapper : IObjectToObjectMapper
{
private Model11 _model;
public string Name => "ManualCtorMapper";
public void Initialize()
{
_model = new Model11 { Value = 5 };
}
public object Map()
{
return new Dto11(_model.Value);
}
}
public class FlatteningMapper : IObjectToObjectMapper
{
private ModelObject _source;
private IMapper _mapper;
public string Name
{
get { return "AutoMapper"; }
}
public void Initialize()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Model1, Dto1>();
cfg.CreateMap<Model2, Dto2>();
cfg.CreateMap<Model3, Dto3>();
cfg.CreateMap<Model4, Dto4>();
cfg.CreateMap<Model5, Dto5>();
cfg.CreateMap<Model6, Dto6>();
cfg.CreateMap<Model7, Dto7>();
cfg.CreateMap<Model8, Dto8>();
cfg.CreateMap<Model9, Dto9>();
cfg.CreateMap<Model10, Dto10>();
cfg.CreateMap<ModelObject, ModelDto>();
});
config.AssertConfigurationIsValid();
_mapper = config.CreateMapper();
_source = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
};
}
public object Map()
{
return _mapper.Map<ModelObject, ModelDto>(_source);
}
}
public class ManualMapper : IObjectToObjectMapper
{
private ModelObject _source;
public string Name
{
get { return "Manual"; }
}
public void Initialize()
{
_source = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
};
}
public object Map()
{
return new ModelDto
{
BaseDate = _source.BaseDate,
Sub2ProperName = _source.Sub2.ProperName,
SubProperName = _source.Sub.ProperName,
SubSubSubIAmACoolProperty = _source.Sub.SubSub.IAmACoolProperty,
SubWithExtraNameProperName = _source.SubWithExtraName.ProperName
};
}
}
public class Model1
{
public int Value { get; set; }
}
public class Model2
{
public int Value { get; set; }
}
public class Model3
{
public int Value { get; set; }
}
public class Model4
{
public int Value { get; set; }
}
public class Model5
{
public int Value { get; set; }
}
public class Model6
{
public int Value { get; set; }
}
public class Model7
{
public int Value { get; set; }
}
public class Model8
{
public int Value { get; set; }
}
public class Model9
{
public int Value { get; set; }
}
public class Model10
{
public int Value { get; set; }
}
public class Model11
{
public int Value { get; set; }
}
public class Dto1
{
public int Value { get; set; }
}
public class Dto2
{
public int Value { get; set; }
}
public class Dto3
{
public int Value { get; set; }
}
public class Dto4
{
public int Value { get; set; }
}
public class Dto5
{
public int Value { get; set; }
}
public class Dto6
{
public int Value { get; set; }
}
public class Dto7
{
public int Value { get; set; }
}
public class Dto8
{
public int Value { get; set; }
}
public class Dto9
{
public int Value { get; set; }
}
public class Dto10
{
public int Value { get; set; }
}
public class Dto11
{
public Dto11(int value)
{
_value = value;
}
private readonly int _value;
public int Value
{
get { return _value; }
}
}
public class ModelObject
{
public DateTime BaseDate { get; set; }
public ModelSubObject Sub { get; set; }
public ModelSubObject Sub2 { get; set; }
public ModelSubObject SubWithExtraName { get; set; }
}
public class ModelSubObject
{
public string ProperName { get; set; }
public ModelSubSubObject SubSub { get; set; }
}
public class ModelSubSubObject
{
public string IAmACoolProperty { get; set; }
}
public class ModelDto
{
public DateTime BaseDate { get; set; }
public string SubProperName { get; set; }
public string Sub2ProperName { get; set; }
public string SubWithExtraNameProperName { get; set; }
public string SubSubSubIAmACoolProperty { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using esmesim.Properties;
using System.Threading;
using System.Diagnostics;
using esmesim.smpp;
using System.Runtime.InteropServices;
namespace esmesim
{
public partial class Form1 : Form
{
private static bool IsRunningOnMono()
{
return Type.GetType("Mono.Runtime") != null;
}
class MessageGridModel
{
public MessageGridModel(string from, string to, string message)
{
m_from = from;
m_to = to;
m_msg = message;
}
public string From { get { return m_from; } }
public string To { get { return m_to; } }
public string Message { get { return m_msg; } }
string m_from, m_to, m_msg;
}
const int keepAliveTime = 55;
private object m_keepAliveLock = new object();
//private EsmeSession session = null;
private smpp.SMPPClient m_client = null;
private BindingList<MessageGridModel> m_inbox = new BindingList<MessageGridModel>();
private BindingList<MessageGridModel> m_outbox = new BindingList<MessageGridModel>();
public Form1()
{
string[] dataCodingValues = Enum.GetValues(typeof(DataCoding)).OfType<object>().Select(o => o.ToString()).ToArray();
InitializeComponent();
cboMode.DataSource = Enum.GetValues(typeof(BindType));
cboMode.SelectedItem = Settings.Default.BindMode;
cboDataCoding.DataSource = dataCodingValues;
cboDataCoding.SelectedItem = dataCodingValues[0];
cboServerDataCoding.DataSource = dataCodingValues;
cboServerDataCoding.SelectedItem = dataCodingValues[0];
chk7bitPacking.Checked = Settings.Default.Gsm7bitPacking;
txtUser.Text = Settings.Default.User;
txtPass.Text = Settings.Default.Password;
txtServer.Text = Settings.Default.ServerAddress;
txtPort.Text = Settings.Default.ServerPort.ToString();
txtAddress.Text = Settings.Default.AddressRange;
txtSystemType.Text = Settings.Default.SystemType;
txtTo.Text = Settings.Default.LastPhoneNumber;
gridInbox.AutoGenerateColumns = false;
gridOutbox.AutoGenerateColumns = false;
gridInbox.DataSource = m_inbox;
gridOutbox.DataSource = m_outbox;
gridInbox.ColumnHeadersBorderStyle = ProperColumnHeadersBorderStyle;
gridOutbox.ColumnHeadersBorderStyle = ProperColumnHeadersBorderStyle;
CheckForIllegalCrossThreadCalls = false;
}
private DataCoding GetSelectedDataCoding(ComboBox combo)
{
return (DataCoding)Enum.Parse(typeof(DataCoding), (string)combo.SelectedItem);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (m_client != null)
{
if (m_client.Bound)
{
m_client.Unbind();
}
m_client.Dispose();
m_client = null;
}
ushort port;
if (ushort.TryParse(txtPort.Text, out port))
{
Settings.Default.ServerPort = port;
}
Settings.Default.User = txtUser.Text;
Settings.Default.Password = txtPass.Text;
Settings.Default.ServerAddress = txtServer.Text;
Settings.Default.BindMode = (BindType)cboMode.SelectedItem;
Settings.Default.AddressRange = txtAddress.Text;
Settings.Default.SystemType = txtSystemType.Text;
Settings.Default.LastPhoneNumber = txtTo.Text;
Settings.Default.DataCoding = GetSelectedDataCoding(cboDataCoding);
Settings.Default.ServerDataCoding = GetSelectedDataCoding(cboServerDataCoding);
Settings.Default.Gsm7bitPacking = chk7bitPacking.Checked;
Settings.Default.Save();
}
private void btnBind_Click(object sender, EventArgs e)
{
if (m_client == null)
{
m_client = new esmesim.smpp.SMPPClient();
m_client.ConnectionLost += new esmesim.smpp.ConnectionLostEventHandler(delegate()
{
MessageBox.Show(this, "Connection with the server has been lost!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
SetInitialStatus(false);
});
m_client.NewMessage += new esmesim.smpp.NewMessageEventHandler(delegate(string from, string to, string content)
{
m_inbox.Add(new MessageGridModel(from, to, content));
});
}
if (m_client.Bound)
{
m_client.Unbind();
}
else
{
ushort port;
if (!ushort.TryParse(txtPort.Text, out port))
{
MessageBox.Show(this, "Server port is invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
m_client.SystemId = txtUser.Text;
m_client.Password = txtPass.Text;
m_client.SystemType = txtSystemType.Text;
m_client.Settings.EnableGSM7bitPacking = chk7bitPacking.Checked;
m_client.Settings.DeliverDataCoding = GetSelectedDataCoding(cboDataCoding);
m_client.Settings.ServerDefaultEncoding = GetSelectedDataCoding(cboServerDataCoding);
m_client.Addresses.Clear();
foreach (string s in txtAddress.Text.Split(','))
{
m_client.Addresses.Add(s);
}
try
{
m_client.Bind((esmesim.smpp.BindType)cboMode.SelectedItem, txtServer.Text, port);
this.BringToFront();
//TODO new Thread(KeepAliveThread
//TODO session.SetDataCoding((DataCoding)cboDataCoding.SelectedItem, (DataCoding)cboServerDataCoding.SelectedItem, chk7bitPacking.Checked);
}
catch (esmesim.smpp.BindException ex)
{
MessageBox.Show(this, "Bind error: " + ex.Result, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
SetInitialStatus(m_client.Bound);
}
private void btnSend_Click(object sender, EventArgs e)
{
SendMessage();
}
bool handleKey = false; // workaround for mono bug
private void txtMessage_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && !e.Shift)
{
e.Handled = true; // mono: you suck on this!
// Mono does not stop the event propagation when e.Handled is set to true
handleKey = true;
SendMessage();
}
}
private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)
{
if (handleKey)
{
e.Handled = true;
handleKey = false;
}
}
private void ShowError(Exception ex)
{
MessageBox.Show(this, ex.Message, ex.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private new void BringToFront()
{
this.TopMost = true;
base.BringToFront();
this.TopMost = false;
}
private void KeepAliveThread()
{
#if FALSE
lock (m_keepAliveLock)
{
for (; ; )
{
try
{
for (int timeout = keepAliveTime * 2; timeout > 0 && session != null; timeout--)
{
Thread.Sleep(500);
}
lock (this)
{
if (session == null)
{
return;
}
session.SendKeepAlive();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
#endif
}
private void SetInitialStatus(bool connected)
{
grLogin.Enabled = !connected;
grMessages.Enabled = connected;
btnBind.Text = connected ? "Unbind" : "Bind";
lblStatus.Text = String.Format("Status: {0}Bound", connected ? "" : "Not ");
lblStatus.ForeColor = connected ? Color.Green : SystemColors.ControlText;
}
private void SendMessage()
{
if (m_client == null)
{
return;
}
try
{
string from = m_client.Addresses.Count == 0 ? String.Empty : m_client.Addresses.ElementAt(0).Split('-')[0];
m_client.SendMessage(from, txtTo.Text, txtMessage.Text);
m_outbox.Add(new MessageGridModel("", txtTo.Text, txtMessage.Text));
}
catch (esmesim.smpp.DeliveryException ex)
{
MessageBox.Show(this, "Could not send message: " + ex.Result, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
static DataGridViewHeaderBorderStyle ProperColumnHeadersBorderStyle
{
get
{
return (SystemFonts.MessageBoxFont.Name == "Segoe UI") ?
DataGridViewHeaderBorderStyle.None : DataGridViewHeaderBorderStyle.Raised;
}
}
private void grid_MouseDoubleClick(object sender, MouseEventArgs e)
{
DataGridView grid = sender as DataGridView;
DataGridView.HitTestInfo hti = grid.HitTest(e.X, e.Y);
if (hti.RowIndex >= 0 && hti.RowIndex < grid.Rows.Count)
{
txtTo.Text = grid.Rows[hti.RowIndex].Cells[0].Value.ToString();
if (grid == gridInbox)
{
txtMessage.Text = grid.Rows[hti.RowIndex].Cells[2].Value.ToString();
}
else
{
txtMessage.Text = grid.Rows[hti.RowIndex].Cells[1].Value.ToString();
}
}
}
private void dataCoding_SelectionChanged(object sender, EventArgs e)
{
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using EverReader.Models;
namespace EverReader.Migrations
{
[DbContext(typeof(EverReaderContext))]
[Migration("20151112123508_AdjustUsersLink")]
partial class AdjustUsersLink
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.Annotation("ProductVersion", "7.0.0-beta8-15964")
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("EverReader.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.Annotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<int?>("EvernoteCredentialsId");
b.Property<bool>("HasAuthorisedEvernote");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.Annotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.Annotation("MaxLength", 256);
b.HasKey("Id");
b.Index("NormalizedEmail")
.Annotation("Relational:Name", "EmailIndex");
b.Index("NormalizedUserName")
.Annotation("Relational:Name", "UserNameIndex");
b.Annotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("EverReader.Models.EFDbEvernoteCredentials", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AuthToken");
b.Property<DateTime>("Expires");
b.Property<string>("NotebookUrl");
b.Property<string>("Shard");
b.Property<string>("UserId");
b.Property<string>("WebApiUrlPrefix");
b.HasKey("Id");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.Annotation("MaxLength", 256);
b.HasKey("Id");
b.Index("NormalizedName")
.Annotation("Relational:Name", "RoleNameIndex");
b.Annotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId");
b.HasKey("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId");
b.HasKey("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.ForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.ForeignKey("RoleId");
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonArrayContract : JsonContainerContract
{
/// <summary>
/// Gets the <see cref="Type"/> of the collection items.
/// </summary>
/// <value>The <see cref="Type"/> of the collection items.</value>
public Type CollectionItemType { get; private set; }
/// <summary>
/// Gets a value indicating whether the collection type is a multidimensional array.
/// </summary>
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; private set; }
private readonly bool _isCollectionItemTypeNullableType;
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private MethodCall<object, object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool IsArray { get; private set; }
internal bool ShouldCreateWrapper { get; private set; }
internal bool CanDeserialize { get; private set; }
internal MethodBase ParametrizedConstructor { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonArrayContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Array;
IsArray = CreatedType.IsArray;
bool canDeserialize;
Type tempCollectionType;
if (IsArray)
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
IsReadOnlyOrFixedSize = true;
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
canDeserialize = true;
IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1);
}
else if (typeof(IList).IsAssignableFrom(underlyingType))
{
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
else
CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
if (underlyingType == typeof(IList))
CreatedType = typeof(List<object>);
if (CollectionItemType != null)
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>));
canDeserialize = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
#if !(NET20 || NET35 || PORTABLE40)
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>)))
CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType);
#endif
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
canDeserialize = true;
ShouldCreateWrapper = true;
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType))
{
CollectionItemType = underlyingType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>)))
CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType);
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(CreatedType, CollectionItemType);
IsReadOnlyOrFixedSize = true;
canDeserialize = (ParametrizedConstructor != null);
}
#endif
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
_genericCollectionDefinitionType = tempCollectionType;
IsReadOnlyOrFixedSize = false;
ShouldCreateWrapper = false;
canDeserialize = true;
}
else
{
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
IsReadOnlyOrFixedSize = true;
ShouldCreateWrapper = true;
canDeserialize = (ParametrizedConstructor != null);
}
}
else
{
// types that implement IEnumerable and nothing else
canDeserialize = false;
ShouldCreateWrapper = true;
}
CanDeserialize = canDeserialize;
if (CollectionItemType != null)
_isCollectionItemTypeNullableType = ReflectionUtils.IsNullableType(CollectionItemType);
#if (NET20 || NET35)
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (_isCollectionItemTypeNullableType
&& (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray)))
{
ShouldCreateWrapper = true;
}
#endif
#if !(NET20 || NET35 || NET40 || PORTABLE40)
Type immutableCreatedType;
MethodBase immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
ParametrizedConstructor = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
CanDeserialize = true;
}
#endif
}
internal IWrappedCollection CreateWrapper(object list)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType);
Type constructorArgument;
if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>))
|| _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType);
else
constructorArgument = _genericCollectionDefinitionType;
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(genericWrapperConstructor);
}
return (IWrappedCollection)_genericWrapperCreator(null, list);
}
internal IList CreateTemporaryCollection()
{
if (_genericTemporaryCollectionCreator == null)
{
// multidimensional array will also have array instances in it
Type collectionItemType = (IsMultidimensionalArray) ? typeof(object) : CollectionItemType;
Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType);
_genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType);
}
return (IList)_genericTemporaryCollectionCreator();
}
}
}
| |
// 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.Threading.Tasks;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class IfKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor1()
{
await VerifyAbsenceAsync(AddInsideMethod(
"#if $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHash()
{
await VerifyKeywordAsync(
@"#$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHashFollowedBySkippedTokens()
{
await VerifyKeywordAsync(
@"#$$
aeu");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHashAndSpace()
{
await VerifyKeywordAsync(
@"# $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideMethod()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$
return true;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return true;
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (true) {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCase()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
case 0:
$$
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCaseBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
case 0: {
$$
}
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefaultCase()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
default:
$$
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefaultCaseBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
default: {
$$
}
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLabel()
{
await VerifyKeywordAsync(AddInsideMethod(
@"label:
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDoBlock()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"do {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInActiveRegion1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"#if true
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInActiveRegion2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"#if true
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterElse()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (foo) {
} else $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatch()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclaration1()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch (Exception) $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclaration2()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch (Exception e) $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclarationEmpty()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch () $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterTryBlock()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} $$"));
}
}
}
| |
/*
* Copyright (c) .NET Foundation and Contributors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Piranha.Models;
namespace Piranha.Services
{
public interface IPostService
{
/// <summary>
/// Creates and initializes a new post of the specified type.
/// </summary>
/// <returns>The created post</returns>
Task<T> CreateAsync<T>(string typeId = null) where T : PostBase;
/// <summary>
/// Gets the available posts for the specified blog.
/// </summary>
/// <param name="blogId">The unique blog id</param>
/// <param name="index">The optional page to fetch</param>
/// <param name="pageSize">The optional page size</param>
/// <returns>The posts</returns>
Task<IEnumerable<DynamicPost>> GetAllAsync(Guid blogId, int? index = null, int? pageSize = null);
/// <summary>
/// Gets the available post items.
/// </summary>
/// <param name="blogId">The unique id</param>
/// <param name="index">The optional page to fetch</param>
/// <param name="pageSize">The optional page size</param>
/// <returns>The posts</returns>
Task<IEnumerable<T>> GetAllAsync<T>(Guid blogId, int? index = null, int? pageSize = null) where T : PostBase;
/// <summary>
/// Gets the available posts for the specified blog.
/// </summary>
/// <param name="siteId">The optional site id</param>
/// <returns>The posts</returns>
Task<IEnumerable<DynamicPost>> GetAllBySiteIdAsync(Guid? siteId = null);
/// <summary>
/// Gets the available post items.
/// </summary>
/// <param name="siteId">The optional site id</param>
/// <returns>The posts</returns>
Task<IEnumerable<T>> GetAllBySiteIdAsync<T>(Guid? siteId = null) where T : PostBase;
/// <summary>
/// Gets the available posts for the specified blog.
/// </summary>
/// <param name="slug">The blog slug</param>
/// <param name="siteId">The optional site id</param>
/// <returns>The posts</returns>
Task<IEnumerable<DynamicPost>> GetAllAsync(string slug, Guid? siteId = null);
/// <summary>
/// Gets the available posts for the specified blog.
/// </summary>
/// <param name="slug">The blog slug</param>
/// <param name="siteId">The optional site id</param>
/// <returns>The posts</returns>
Task<IEnumerable<T>> GetAllAsync<T>(string slug, Guid? siteId = null) where T : PostBase;
/// <summary>
/// Gets all available categories for the specified blog.
/// </summary>
/// <param name="blogId">The blog id</param>
/// <returns>The available categories</returns>
Task<IEnumerable<Taxonomy>> GetAllCategoriesAsync(Guid blogId);
/// <summary>
/// Gets all available tags for the specified blog.
/// </summary>
/// <param name="blogId">The blog id</param>
/// <returns>The available tags</returns>
Task<IEnumerable<Taxonomy>> GetAllTagsAsync(Guid blogId);
/// <summary>
/// Gets the id of all posts that have a draft for
/// the specified blog.
/// </summary>
/// <param name="blogId">The blog id</param>
/// <returns>The posts that have a draft</returns>
Task<IEnumerable<Guid>> GetAllDraftsAsync(Guid blogId);
/// <summary>
/// Gets the comments available for the post with the specified id. If no post id
/// is provided all comments are fetched.
/// </summary>
/// <param name="postId">The unique post id</param>
/// <param name="onlyApproved">If only approved comments should be fetched</param>
/// <param name="page">The optional page number</param>
/// <param name="pageSize">The optional page size</param>
/// <returns>The available comments</returns>
Task<IEnumerable<Comment>> GetAllCommentsAsync(Guid? postId = null, bool onlyApproved = true,
int? page = null, int? pageSize = null);
/// <summary>
/// Gets the pending comments available for the post with the specified id. If no post id
/// is provided all comments are fetched.
/// </summary>
/// <param name="postId">The unique post id</param>
/// <param name="page">The optional page number</param>
/// <param name="pageSize">The optional page size</param>
/// <returns>The available comments</returns>
Task<IEnumerable<Comment>> GetAllPendingCommentsAsync(Guid? postId = null,
int? page = null, int? pageSize = null);
/// <summary>
/// Gets the number of available posts in the specified archive.
/// </summary>
/// <param name="archiveId">The archive id</param>
/// <returns>The number of posts</returns>
Task<int> GetCountAsync(Guid archiveId);
/// <summary>
/// Gets the post model with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
/// <returns>The post model</returns>
Task<DynamicPost> GetByIdAsync(Guid id);
/// <summary>
/// Gets the post model with the specified id.
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="id">The unique id</param>
/// <returns>The post model</returns>
Task<T> GetByIdAsync<T>(Guid id) where T : PostBase;
/// <summary>
/// Gets the draft for the post model with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
/// <returns>The draft, or null if no draft exists</returns>
Task<DynamicPost> GetDraftByIdAsync(Guid id);
/// <summary>
/// Gets the draft for the post model with the specified id.
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="id">The unique id</param>
/// <returns>The draft, or null if no draft exists</returns>
Task<T> GetDraftByIdAsync<T>(Guid id) where T : PostBase;
/// <summary>
/// Gets the post model with the specified slug.
/// </summary>
/// <param name="blog">The unique blog slug</param>
/// <param name="slug">The unique slug</param>
/// <param name="siteId">The optional site id</param>
/// <returns>The post model</returns>
Task<DynamicPost> GetBySlugAsync(string blog, string slug, Guid? siteId = null);
/// <summary>
/// Gets the post model with the specified slug.
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="blog">The unique blog slug</param>
/// <param name="slug">The unique slug</param>
/// <param name="siteId">The optional site id</param>
/// <returns>The post model</returns>
Task<T> GetBySlugAsync<T>(string blog, string slug, Guid? siteId = null) where T : PostBase;
/// <summary>
/// Gets the post model with the specified slug.
/// </summary>
/// <param name="blogId">The unique blog slug</param>
/// <param name="slug">The unique slug</param>
/// <returns>The post model</returns>
Task<DynamicPost> GetBySlugAsync(Guid blogId, string slug);
/// <summary>
/// Gets the post model with the specified slug.
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="blogId">The unique blog slug</param>
/// <param name="slug">The unique slug</param>
/// <returns>The post model</returns>
Task<T> GetBySlugAsync<T>(Guid blogId, string slug) where T : PostBase;
/// <summary>
/// Gets the category with the id.
/// </summary>
/// <param name="id">The unique id</param>
/// <returns>The model</returns>
Task<Taxonomy> GetCategoryByIdAsync(Guid id);
/// <summary>
/// Gets the category with the given slug.
/// </summary>
/// <param name="blogId">The blog id</param>
/// <param name="slug">The unique slug</param>
/// <returns>The model</returns>
Task<Taxonomy> GetCategoryBySlugAsync(Guid blogId, string slug);
/// <summary>
/// Gets the tag with the id.
/// </summary>
/// <param name="id">The unique id</param>
/// <returns>The model</returns>
Task<Taxonomy> GetTagByIdAsync(Guid id);
/// <summary>
/// Gets the tag with the given slug.
/// </summary>
/// <param name="blogId">The blog id</param>
/// <param name="slug">The unique slug</param>
/// <returns>The model</returns>
Task<Taxonomy> GetTagBySlugAsync(Guid blogId, string slug);
/// <summary>
/// Gets the comment with the given id.
/// </summary>
/// <param name="id">The comment id</param>
/// <returns>The model</returns>
Task<Comment> GetCommentByIdAsync(Guid id);
/// <summary>
/// Saves the given post model.
/// </summary>
/// <param name="model">The post model</param>
Task SaveAsync<T>(T model) where T : PostBase;
/// <summary>
/// Saves the given post model as a draft
/// </summary>
/// <param name="model">The post model</param>
Task SaveDraftAsync<T>(T model) where T : PostBase;
/// <summary>
/// Saves the comment.
/// </summary>
/// <param name="model">The comment model</param>
/// <param name="postId">The unique post id</param>
Task SaveCommentAsync(Guid postId, Comment model);
/// <summary>
/// Saves the comment and verifies if should be approved or not.
/// </summary>
/// <param name="model">The comment model</param>
/// <param name="postId">The unique post id</param>
Task SaveCommentAndVerifyAsync(Guid postId, Comment model);
/// <summary>
/// Deletes the model with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
Task DeleteAsync(Guid id);
/// <summary>
/// Deletes the given model.
/// </summary>
/// <param name="model">The model</param>
Task DeleteAsync<T>(T model) where T : PostBase;
/// <summary>
/// Deletes the comment with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
Task DeleteCommentAsync(Guid id);
/// <summary>
/// Deletes the given comment.
/// </summary>
/// <param name="model">The comment</param>
Task DeleteCommentAsync(Comment model);
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SceneCaptureComponent2D.h:20
namespace UnrealEngine
{
[ManageType("ManageSceneCaptureComponent2D")]
public partial class ManageSceneCaptureComponent2D : USceneCaptureComponent2D, IManageWrapper
{
public ManageSceneCaptureComponent2D(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnAttachmentChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnHiddenInGameChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnVisibilityChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PropagateLightingScenarioChange(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_UpdateBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__USceneCaptureComponent2D_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// DEPRECATED - Use DetachFromComponent() instead
/// </summary>
public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify)
=> E__Supper__USceneCaptureComponent2D_DetachFromParent(this, bMaintainWorldPosition, bCallModify);
/// <summary>
/// Called when AttachParent changes, to allow the scene to update its attachment state.
/// </summary>
public override void OnAttachmentChanged()
=> E__Supper__USceneCaptureComponent2D_OnAttachmentChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the hidden in game value of the component.
/// </summary>
protected override void OnHiddenInGameChanged()
=> E__Supper__USceneCaptureComponent2D_OnHiddenInGameChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the visibility of the component.
/// </summary>
protected override void OnVisibilityChanged()
=> E__Supper__USceneCaptureComponent2D_OnVisibilityChanged(this);
/// <summary>
/// Updates any visuals after the lighting has changed
/// </summary>
public override void PropagateLightingScenarioChange()
=> E__Supper__USceneCaptureComponent2D_PropagateLightingScenarioChange(this);
/// <summary>
/// Update the Bounds of the component.
/// </summary>
public override void UpdateBounds()
=> E__Supper__USceneCaptureComponent2D_UpdateBounds(this);
/// <summary>
/// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true.
/// </summary>
/// <param name="bTriggerNotifiers">if true, send zone/volume change events</param>
public override void UpdatePhysicsVolume(bool bTriggerNotifiers)
=> E__Supper__USceneCaptureComponent2D_UpdatePhysicsVolume(this, bTriggerNotifiers);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__USceneCaptureComponent2D_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__USceneCaptureComponent2D_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__USceneCaptureComponent2D_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__USceneCaptureComponent2D_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__USceneCaptureComponent2D_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__USceneCaptureComponent2D_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__USceneCaptureComponent2D_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__USceneCaptureComponent2D_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__USceneCaptureComponent2D_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__USceneCaptureComponent2D_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__USceneCaptureComponent2D_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__USceneCaptureComponent2D_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__USceneCaptureComponent2D_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__USceneCaptureComponent2D_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__USceneCaptureComponent2D_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__USceneCaptureComponent2D_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__USceneCaptureComponent2D_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__USceneCaptureComponent2D_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__USceneCaptureComponent2D_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__USceneCaptureComponent2D_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__USceneCaptureComponent2D_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__USceneCaptureComponent2D_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__USceneCaptureComponent2D_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__USceneCaptureComponent2D_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__USceneCaptureComponent2D_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__USceneCaptureComponent2D_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__USceneCaptureComponent2D_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__USceneCaptureComponent2D_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__USceneCaptureComponent2D_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__USceneCaptureComponent2D_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__USceneCaptureComponent2D_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__USceneCaptureComponent2D_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__USceneCaptureComponent2D_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__USceneCaptureComponent2D_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__USceneCaptureComponent2D_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__USceneCaptureComponent2D_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__USceneCaptureComponent2D_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__USceneCaptureComponent2D_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__USceneCaptureComponent2D_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__USceneCaptureComponent2D_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageSceneCaptureComponent2D self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageSceneCaptureComponent2D(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageSceneCaptureComponent2D>(PtrDesc);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Clients;
using OpenSim.Region.Communications.OGS1;
using OpenSim.Region.Communications.Local;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Communications.Hypergrid
{
/// <summary>
/// For the time being, this class is just an identity wrapper around OGS1UserServices,
/// so it always fails for foreign users.
/// Later it needs to talk with the foreign users' user servers.
/// </summary>
public class HGUserServices : OGS1UserServices
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//private OGS1UserServices m_remoteUserServices;
private LocalUserServices m_localUserServices;
// Constructor called when running in grid mode
public HGUserServices(CommunicationsManager commsManager)
: base(commsManager)
{
}
// Constructor called when running in standalone
public HGUserServices(CommunicationsManager commsManager, LocalUserServices local)
: base(commsManager)
{
m_localUserServices = local;
}
public override void SetInventoryService(IInventoryService invService)
{
base.SetInventoryService(invService);
if (m_localUserServices != null)
m_localUserServices.SetInventoryService(invService);
}
public override UUID AddUser(
string firstName, string lastName, string password, string email, uint regX, uint regY, UUID uuid)
{
// Only valid to create users locally
if (m_localUserServices != null)
return m_localUserServices.AddUser(firstName, lastName, password, email, regX, regY, uuid);
return UUID.Zero;
}
public override bool AddUserAgent(UserAgentData agentdata)
{
if (m_localUserServices != null)
return m_localUserServices.AddUserAgent(agentdata);
return base.AddUserAgent(agentdata);
}
public override UserAgentData GetAgentByUUID(UUID userId)
{
string url = string.Empty;
if ((m_localUserServices != null) && !IsForeignUser(userId, out url))
return m_localUserServices.GetAgentByUUID(userId);
return base.GetAgentByUUID(userId);
}
public override void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
{
string url = string.Empty;
if ((m_localUserServices != null) && !IsForeignUser(userid, out url))
m_localUserServices.LogOffUser(userid, regionid, regionhandle, position, lookat);
else
base.LogOffUser(userid, regionid, regionhandle, position, lookat);
}
public override UserProfileData GetUserProfile(string firstName, string lastName)
{
if (m_localUserServices != null)
return m_localUserServices.GetUserProfile(firstName, lastName);
return base.GetUserProfile(firstName, lastName);
}
public override List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
{
if (m_localUserServices != null)
return m_localUserServices.GenerateAgentPickerRequestResponse(queryID, query);
return base.GenerateAgentPickerRequestResponse(queryID, query);
}
/// <summary>
/// Get a user profile from the user server
/// </summary>
/// <param name="avatarID"></param>
/// <returns>null if the request fails</returns>
public override UserProfileData GetUserProfile(UUID avatarID)
{
//string url = string.Empty;
// Unfortunately we can't query for foreigners here,
// because we'll end up in an infinite loop...
//if ((m_localUserServices != null) && (!IsForeignUser(avatarID, out url)))
if (m_localUserServices != null)
return m_localUserServices.GetUserProfile(avatarID);
return base.GetUserProfile(avatarID);
}
public override void ClearUserAgent(UUID avatarID)
{
if (m_localUserServices != null)
m_localUserServices.ClearUserAgent(avatarID);
else
base.ClearUserAgent(avatarID);
}
/// <summary>
/// Retrieve the user information for the given master uuid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
public override UserProfileData SetupMasterUser(string firstName, string lastName)
{
if (m_localUserServices != null)
return m_localUserServices.SetupMasterUser(firstName, lastName);
return base.SetupMasterUser(firstName, lastName);
}
/// <summary>
/// Retrieve the user information for the given master uuid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
public override UserProfileData SetupMasterUser(string firstName, string lastName, string password)
{
if (m_localUserServices != null)
return m_localUserServices.SetupMasterUser(firstName, lastName, password);
return base.SetupMasterUser(firstName, lastName, password);
}
/// <summary>
/// Retrieve the user information for the given master uuid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
public override UserProfileData SetupMasterUser(UUID uuid)
{
if (m_localUserServices != null)
return m_localUserServices.SetupMasterUser(uuid);
return base.SetupMasterUser(uuid);
}
public override bool ResetUserPassword(string firstName, string lastName, string newPassword)
{
if (m_localUserServices != null)
return m_localUserServices.ResetUserPassword(firstName, lastName, newPassword);
else
return base.ResetUserPassword(firstName, lastName, newPassword);
}
public override bool UpdateUserProfile(UserProfileData userProfile)
{
string url = string.Empty;
if ((m_localUserServices != null) && (!IsForeignUser(userProfile.ID, out url)))
return m_localUserServices.UpdateUserProfile(userProfile);
return base.UpdateUserProfile(userProfile);
}
#region IUserServices Friend Methods
// NOTE: We're still not dealing with foreign user friends
/// <summary>
/// Adds a new friend to the database for XUser
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being added to</param>
/// <param name="friend">The agent that being added to the friends list of the friends list owner</param>
/// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
public override void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
{
if (m_localUserServices != null)
m_localUserServices.AddNewUserFriend(friendlistowner, friend, perms);
else
base.AddNewUserFriend(friendlistowner, friend, perms);
}
/// <summary>
/// Delete friend on friendlistowner's friendlist.
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being updated</param>
/// <param name="friend">The Ex-friend agent</param>
public override void RemoveUserFriend(UUID friendlistowner, UUID friend)
{
if (m_localUserServices != null)
m_localUserServices.RemoveUserFriend(friendlistowner, friend);
else
base.RemoveUserFriend(friend, friend);
}
/// <summary>
/// Update permissions for friend on friendlistowner's friendlist.
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being updated</param>
/// <param name="friend">The agent that is getting or loosing permissions</param>
/// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
public override void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
{
if (m_localUserServices != null)
m_localUserServices.UpdateUserFriendPerms(friendlistowner, friend, perms);
else
base.UpdateUserFriendPerms(friendlistowner, friend, perms);
}
/// <summary>
/// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner
/// </summary>
/// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param>
public override List<FriendListItem> GetUserFriendList(UUID friendlistowner)
{
if (m_localUserServices != null)
return m_localUserServices.GetUserFriendList(friendlistowner);
return base.GetUserFriendList(friendlistowner);
}
#endregion
/// Appearance
public override AvatarAppearance GetUserAppearance(UUID user)
{
string url = string.Empty;
if ((m_localUserServices != null) && (!IsForeignUser(user, out url)))
return m_localUserServices.GetUserAppearance(user);
else
return base.GetUserAppearance(user);
}
public override void UpdateUserAppearance(UUID user, AvatarAppearance appearance)
{
string url = string.Empty;
if ((m_localUserServices != null) && (!IsForeignUser(user, out url)))
m_localUserServices.UpdateUserAppearance(user, appearance);
else
base.UpdateUserAppearance(user, appearance);
}
#region IMessagingService
public override Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
{
if (m_localUserServices != null)
return m_localUserServices.GetFriendRegionInfos(uuids);
return base.GetFriendRegionInfos(uuids);
}
#endregion
public override bool VerifySession(UUID userID, UUID sessionID)
{
string url = string.Empty;
if ((m_localUserServices != null) && (!IsForeignUser(userID, out url)))
return m_localUserServices.VerifySession(userID, sessionID);
else
return base.VerifySession(userID, sessionID);
}
protected override string GetUserServerURL(UUID userID)
{
string serverURL = string.Empty;
if (IsForeignUser(userID, out serverURL))
return serverURL;
return m_commsManager.NetworkServersInfo.UserURL;
}
private bool IsForeignUser(UUID userID, out string userServerURL)
{
userServerURL = string.Empty;
CachedUserInfo uinfo = m_commsManager.UserProfileCacheService.GetUserDetails(userID);
if (uinfo != null)
{
if (!HGNetworkServersInfo.Singleton.IsLocalUser(uinfo.UserProfile))
{
userServerURL = ((ForeignUserProfileData)(uinfo.UserProfile)).UserServerURI;
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.DotNet.VersionTools.Dependencies;
namespace Dotnet.Docker
{
/// <summary>
/// An IDependencyUpdater that will scan a Dockerfile for the .NET artifacts that are installed.
/// The updater will then retrieve and update the checksum sha used to validate the downloaded artifacts.
/// </summary>
public class DockerfileShaUpdater : FileRegexUpdater
{
private const string ChecksumsHostName = "dotnetclichecksums.blob.core.windows.net";
private const string ShaVariableGroupName = "shaVariable";
private const string ShaValueGroupName = "shaValue";
private static readonly Dictionary<string, string> s_shaCache = new Dictionary<string, string>();
private static readonly Dictionary<string, Dictionary<string, string>> s_releaseChecksumCache =
new Dictionary<string, Dictionary<string, string>>();
private static readonly Dictionary<string, string> s_urls = new Dictionary<string, string> {
{"powershell", "https://pwshtool.blob.core.windows.net/tool/$VERSION_DIR/PowerShell.$OS.$ARCH.$VERSION_FILE.nupkg"},
{"monitor", "https://dotnetcli.azureedge.net/dotnet/diagnostics/monitor5.0/dotnet-monitor.$VERSION_FILE.nupkg"},
{"runtime", "https://dotnetcli.azureedge.net/dotnet/Runtime/$VERSION_DIR/dotnet-runtime-$VERSION_FILE-$OS-$ARCH.$ARCHIVE_EXT"},
{"aspnet", "https://dotnetcli.azureedge.net/dotnet/aspnetcore/Runtime/$VERSION_DIR/aspnetcore-runtime-$VERSION_FILE-$OS-$ARCH.$ARCHIVE_EXT"},
{"sdk", "https://dotnetcli.azureedge.net/dotnet/Sdk/$VERSION_DIR/dotnet-sdk-$VERSION_FILE-$OS-$ARCH.$ARCHIVE_EXT"},
{"lzma", "https://dotnetcli.azureedge.net/dotnet/Sdk/$VERSION_DIR/nuGetPackagesArchive.lzma"}
};
private string _productName;
private string _dockerfileVersion;
private string _buildVersion;
private string _arch;
private string _os;
private Options _options;
private string _versions;
public DockerfileShaUpdater() : base()
{
}
public static IEnumerable<IDependencyUpdater> CreateUpdaters(
string productName, string dockerfileVersion, string repoRoot, Options options)
{
string versionsPath = System.IO.Path.Combine(repoRoot, Program.VersionsFilename);
string versions = File.ReadAllText(versionsPath);
// The format of the sha variable name is '<productName>|<dockerfileVersion>|<os>|<arch>|sha'.
// The 'os' and 'arch' segments are optional.
string shaVariablePattern =
$"\"(?<{ShaVariableGroupName}>{Regex.Escape(productName)}\\|{Regex.Escape(dockerfileVersion)}.*\\|sha)\":";
Regex shaVariableRegex = new Regex(shaVariablePattern);
return shaVariableRegex.Matches(versions)
.Select(match => match.Groups[ShaVariableGroupName].Value)
.Select(variable =>
{
Trace.TraceInformation($"Updating {variable}");
string[] parts = variable.Split('|');
DockerfileShaUpdater updater = new DockerfileShaUpdater()
{
_productName = productName,
_buildVersion = VersionUpdater.GetBuildVersion(productName, dockerfileVersion, versions),
_dockerfileVersion = dockerfileVersion,
_os = parts.Length >= 4 ? parts[2] : string.Empty,
_arch = parts.Length >= 5 ? parts[3] : string.Empty,
_options = options,
_versions = versions,
Path = versionsPath,
VersionGroupName = ShaValueGroupName
};
string archPattern = updater._arch == string.Empty ? string.Empty : "|" + updater._arch;
string osPattern = updater._os == string.Empty ? string.Empty : "|" + updater._os;
updater.Regex = new Regex(
$"{shaVariablePattern.Replace(".*", Regex.Escape(osPattern + archPattern))} \"(?<{ShaValueGroupName}>.*)\"");
return updater;
})
.ToArray();
}
protected override string TryGetDesiredValue(
IEnumerable<IDependencyInfo> dependencyBuildInfos, out IEnumerable<IDependencyInfo> usedBuildInfos)
{
IDependencyInfo productInfo = dependencyBuildInfos.First(info => info.SimpleName == _productName);
usedBuildInfos = new IDependencyInfo[] { productInfo };
const string RtmSubstring = "-rtm.";
string versionDir = _buildVersion;
string versionFile = _buildVersion;
if (versionFile.Contains(RtmSubstring))
{
versionFile = versionFile.Substring(0, versionFile.IndexOf(RtmSubstring));
}
string downloadUrl = s_urls[_productName]
.Replace("$ARCHIVE_EXT", _os.Contains("win") ? "zip" : "tar.gz")
.Replace("$VERSION_DIR", versionDir)
.Replace("$VERSION_FILE", versionFile)
.Replace("$OS", _os)
.Replace("$ARCH", _arch)
.Replace("..", ".");
return GetArtifactShaAsync(downloadUrl).Result;
}
private async Task<string> GetArtifactShaAsync(string downloadUrl)
{
if (!s_shaCache.TryGetValue(downloadUrl, out string sha))
{
sha = await GetDotNetCliChecksumsShaAsync(downloadUrl)
?? await GetDotNetReleaseChecksumsShaAsync(downloadUrl)
?? await ComputeChecksumShaAsync(downloadUrl);
if (sha != null)
{
sha = sha.ToLowerInvariant();
s_shaCache.Add(downloadUrl, sha);
Trace.TraceInformation($"Retrieved sha '{sha}' for '{downloadUrl}'.");
}
else
{
Trace.TraceError($"Unable to retrieve sha for '{downloadUrl}'.");
}
}
return sha;
}
private async Task<string> ComputeChecksumShaAsync(string downloadUrl)
{
if (!_options.ComputeChecksums)
{
return null;
}
string sha = null;
Trace.TraceInformation($"Downloading '{downloadUrl}'.");
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(downloadUrl))
{
if (response.IsSuccessStatusCode)
{
using (Stream httpStream = await response.Content.ReadAsStreamAsync())
using (SHA512 hash = SHA512.Create())
{
byte[] hashedInputBytes = hash.ComputeHash(httpStream);
StringBuilder stringBuilder = new StringBuilder(128);
foreach (byte b in hashedInputBytes)
{
stringBuilder.Append(b.ToString("X2"));
}
sha = stringBuilder.ToString();
}
}
else
{
Trace.TraceInformation($"Failed to download {downloadUrl}.");
}
}
return sha;
}
private async Task<string> GetDotNetCliChecksumsShaAsync(string productDownloadUrl)
{
string sha = null;
string shaExt = _productName.Contains("sdk", StringComparison.OrdinalIgnoreCase) ? ".sha" : ".sha512";
UriBuilder uriBuilder = new UriBuilder(productDownloadUrl)
{
Host = ChecksumsHostName
};
string shaUrl = uriBuilder.ToString() + shaExt;
Trace.TraceInformation($"Downloading '{shaUrl}'.");
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(shaUrl))
{
if (response.IsSuccessStatusCode)
{
sha = await response.Content.ReadAsStringAsync();
}
else
{
Trace.TraceInformation($"Failed to find `dotnetclichecksums` sha");
}
}
return sha;
}
private async Task<string> GetDotNetReleaseChecksumsShaAsync(
string productDownloadUrl)
{
string buildVersion = _buildVersion;
// The release checksum file contains content for all products in the release (runtime, sdk, etc.)
// and is referenced by the runtime version.
if (_productName.Contains("sdk", StringComparison.OrdinalIgnoreCase) ||
_productName.Contains("aspnet", StringComparison.OrdinalIgnoreCase))
{
buildVersion = VersionUpdater.GetBuildVersion("runtime", _dockerfileVersion, _versions);
}
IDictionary<string, string> checksumEntries = await GetDotnetReleaseChecksums(buildVersion);
string installerFileName = productDownloadUrl.Substring(productDownloadUrl.LastIndexOf('/') + 1);
if (!checksumEntries.TryGetValue(installerFileName, out string sha))
{
Trace.TraceInformation($"Failed to find `{installerFileName}` sha");
}
return sha;
}
private static async Task<IDictionary<string, string>> GetDotnetReleaseChecksums(string version)
{
string uri = $"https://dotnetcli.blob.core.windows.net/dotnet/checksums/{version}-sha.txt";
if (s_releaseChecksumCache.TryGetValue(uri, out Dictionary<string, string> checksumEntries))
{
return checksumEntries;
}
checksumEntries = new Dictionary<string, string>();
s_releaseChecksumCache.Add(uri, checksumEntries);
Trace.TraceInformation($"Downloading '{uri}'.");
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(uri))
{
if (response.IsSuccessStatusCode)
{
string checksums = await response.Content.ReadAsStringAsync();
string[] checksumLines = checksums.Replace("\r\n", "\n").Split("\n");
if (!checksumLines[0].StartsWith("Hash") || !string.IsNullOrEmpty(checksumLines[1]))
{
Trace.TraceError($"Checksum file is not in the expected format: {uri}");
}
for (int i = 2; i < checksumLines.Length - 1; i++)
{
string[] parts = checksumLines[i].Split(" ");
if (parts.Length != 2)
{
Trace.TraceError($"Checksum file is not in the expected format: {uri}");
}
string fileName = parts[1];
string checksum = parts[0];
checksumEntries.Add(fileName, checksum);
Trace.TraceInformation($"Parsed checksum '{checksum}' for '{fileName}'");
}
}
else
{
Trace.TraceInformation($"Failed to find dotnet release checksums");
}
}
return checksumEntries;
}
}
}
| |
namespace Epi.Windows.Analysis.Dialogs
{
partial class LogisticRegressionDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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(LogisticRegressionDialog));
this.cmbWeight = new System.Windows.Forms.ComboBox();
this.lblWeight = new System.Windows.Forms.Label();
this.lblOutput = new System.Windows.Forms.Label();
this.txtOutput = new System.Windows.Forms.TextBox();
this.cmbOutcome = new System.Windows.Forms.ComboBox();
this.lblOutcomeVar = new System.Windows.Forms.Label();
this.lbxOther = new System.Windows.Forms.ListBox();
this.btnHelp = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.cmbOther = new System.Windows.Forms.ComboBox();
this.lblOther = new System.Windows.Forms.Label();
this.cmbConfLimits = new System.Windows.Forms.ComboBox();
this.lblConfLimits = new System.Windows.Forms.Label();
this.btnModifyTerm = new System.Windows.Forms.Button();
this.lblDummyVar = new System.Windows.Forms.Label();
this.lblInteractionTerms = new System.Windows.Forms.Label();
this.lbxInteractionTerms = new System.Windows.Forms.ListBox();
this.checkboxNoIntercept = new System.Windows.Forms.CheckBox();
this.btnCancel = new System.Windows.Forms.Button();
this.cmbMatch = new System.Windows.Forms.ComboBox();
this.lblMatch = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
//
// cmbWeight
//
this.cmbWeight.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbWeight, "cmbWeight");
this.cmbWeight.Name = "cmbWeight";
this.cmbWeight.SelectedIndexChanged += new System.EventHandler(this.cmbWeight_SelectedIndexChanged);
this.cmbWeight.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cmbWeight_KeyDown);
//
// lblWeight
//
this.lblWeight.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblWeight, "lblWeight");
this.lblWeight.Name = "lblWeight";
//
// lblOutput
//
this.lblOutput.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblOutput, "lblOutput");
this.lblOutput.Name = "lblOutput";
//
// txtOutput
//
resources.ApplyResources(this.txtOutput, "txtOutput");
this.txtOutput.Name = "txtOutput";
//
// cmbOutcome
//
this.cmbOutcome.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbOutcome, "cmbOutcome");
this.cmbOutcome.Name = "cmbOutcome";
this.cmbOutcome.SelectedIndexChanged += new System.EventHandler(this.cmbOutcome_SelectedIndexChanged);
//
// lblOutcomeVar
//
this.lblOutcomeVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblOutcomeVar, "lblOutcomeVar");
this.lblOutcomeVar.Name = "lblOutcomeVar";
//
// lbxOther
//
resources.ApplyResources(this.lbxOther, "lbxOther");
this.lbxOther.Name = "lbxOther";
this.lbxOther.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this.lbxOther.SelectedIndexChanged += new System.EventHandler(this.lbxOther_SelectedIndexChanged);
this.lbxOther.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lbxOther_KeyDown);
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnClear
//
resources.ApplyResources(this.btnClear, "btnClear");
this.btnClear.Name = "btnClear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
//
// btnSaveOnly
//
resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly");
this.btnSaveOnly.Name = "btnSaveOnly";
//
// cmbOther
//
this.cmbOther.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbOther, "cmbOther");
this.cmbOther.Name = "cmbOther";
this.cmbOther.SelectedIndexChanged += new System.EventHandler(this.cmbOther_SelectedIndexChanged);
//
// lblOther
//
this.lblOther.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.lblOther, "lblOther");
this.lblOther.Name = "lblOther";
//
// cmbConfLimits
//
this.cmbConfLimits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbConfLimits, "cmbConfLimits");
this.cmbConfLimits.Name = "cmbConfLimits";
//
// lblConfLimits
//
this.lblConfLimits.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblConfLimits, "lblConfLimits");
this.lblConfLimits.Name = "lblConfLimits";
//
// btnModifyTerm
//
resources.ApplyResources(this.btnModifyTerm, "btnModifyTerm");
this.btnModifyTerm.Name = "btnModifyTerm";
this.btnModifyTerm.Click += new System.EventHandler(this.btnModifyTerm_Click);
//
// lblDummyVar
//
this.lblDummyVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblDummyVar, "lblDummyVar");
this.lblDummyVar.Name = "lblDummyVar";
//
// lblInteractionTerms
//
resources.ApplyResources(this.lblInteractionTerms, "lblInteractionTerms");
this.lblInteractionTerms.Name = "lblInteractionTerms";
//
// lbxInteractionTerms
//
resources.ApplyResources(this.lbxInteractionTerms, "lbxInteractionTerms");
this.lbxInteractionTerms.Name = "lbxInteractionTerms";
this.lbxInteractionTerms.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lbxInteractionTerms_KeyDown);
//
// checkboxNoIntercept
//
resources.ApplyResources(this.checkboxNoIntercept, "checkboxNoIntercept");
this.checkboxNoIntercept.Name = "checkboxNoIntercept";
this.checkboxNoIntercept.UseVisualStyleBackColor = true;
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// cmbMatch
//
this.cmbMatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbMatch, "cmbMatch");
this.cmbMatch.Name = "cmbMatch";
this.cmbMatch.SelectedIndexChanged += new System.EventHandler(this.cmbMatch_SelectedIndexChanged);
this.cmbMatch.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cmbMatch_KeyDown);
//
// lblMatch
//
this.lblMatch.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblMatch, "lblMatch");
this.lblMatch.Name = "lblMatch";
//
// LogisticRegressionDialog
//
this.AcceptButton = this.btnOK;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.cmbMatch);
this.Controls.Add(this.lblMatch);
this.Controls.Add(this.checkboxNoIntercept);
this.Controls.Add(this.lbxInteractionTerms);
this.Controls.Add(this.lblInteractionTerms);
this.Controls.Add(this.lblDummyVar);
this.Controls.Add(this.btnModifyTerm);
this.Controls.Add(this.cmbConfLimits);
this.Controls.Add(this.lblConfLimits);
this.Controls.Add(this.cmbOther);
this.Controls.Add(this.btnSaveOnly);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.lbxOther);
this.Controls.Add(this.cmbOutcome);
this.Controls.Add(this.lblOutcomeVar);
this.Controls.Add(this.lblOutput);
this.Controls.Add(this.txtOutput);
this.Controls.Add(this.cmbWeight);
this.Controls.Add(this.lblWeight);
this.Controls.Add(this.lblOther);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "LogisticRegressionDialog";
this.Load += new System.EventHandler(this.LinearRegressionDialog_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox cmbWeight;
private System.Windows.Forms.Label lblWeight;
private System.Windows.Forms.Label lblOutput;
private System.Windows.Forms.TextBox txtOutput;
private System.Windows.Forms.ComboBox cmbOutcome;
private System.Windows.Forms.Label lblOutcomeVar;
private System.Windows.Forms.ListBox lbxOther;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnSaveOnly;
private System.Windows.Forms.ComboBox cmbOther;
private System.Windows.Forms.Label lblOther;
private System.Windows.Forms.ComboBox cmbConfLimits;
private System.Windows.Forms.Label lblConfLimits;
private System.Windows.Forms.Button btnModifyTerm;
private System.Windows.Forms.Label lblDummyVar;
private System.Windows.Forms.Label lblInteractionTerms;
private System.Windows.Forms.ListBox lbxInteractionTerms;
private System.Windows.Forms.CheckBox checkboxNoIntercept;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.ComboBox cmbMatch;
private System.Windows.Forms.Label lblMatch;
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: PropertyPathConverter.cs
//
// Description: Contains converter for creating PropertyPath from string
// and saving PropertyPath to string
//
// History:
// 05/15/2004 - peterost - Initial implementation
//
//---------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Text;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;
using MS.Internal;
using MS.Utility;
using MS.Internal.Data;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows
{
/// <summary>
/// PropertyPathConverter - Converter class for converting instances of other types
/// to and from PropertyPath instances.
/// </summary>
public sealed class PropertyPathConverter: TypeConverter
{
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// CanConvertFrom - Returns whether or not this class can convert from a given type.
/// </summary>
/// <returns>
/// bool - True if this converter can convert from the provided type, false if not.
/// </returns>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="sourceType"> The Type being queried for support. </param>
public override bool CanConvertFrom(ITypeDescriptorContext typeDescriptorContext, Type sourceType)
{
// We can only handle strings
if (sourceType == typeof(string))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// CanConvertTo - Returns whether or not this class can convert to a given type.
/// </summary>
/// <returns>
/// bool - True if this converter can convert to the provided type, false if not.
/// </returns>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="destinationType"> The Type being queried for support. </param>
public override bool CanConvertTo(ITypeDescriptorContext typeDescriptorContext, Type destinationType)
{
// We can convert to a string.
if (destinationType == typeof(string))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// ConvertFrom - Attempt to convert to a PropertyPath from the given object
/// </summary>
/// <returns>
/// The PropertyPath which was constructed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the example object is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the example object is not null and is not a valid type
/// which can be converted to a PropertyPath.
/// </exception>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="cultureInfo"> The CultureInfo which is respected when converting. </param>
/// <param name="source"> The object to convert to a PropertyPath. </param>
public override object ConvertFrom(ITypeDescriptorContext typeDescriptorContext,
CultureInfo cultureInfo,
object source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (source is string)
{
return new PropertyPath((string)source, typeDescriptorContext);
}
#pragma warning suppress 6506 // source is obviously not null
throw new ArgumentException(SR.Get(SRID.CannotConvertType, source.GetType().FullName, typeof(PropertyPath)));
}
/// <summary>
/// ConvertTo - Attempt to convert a PropertyPath to the given type
/// </summary>
/// <returns>
/// The object which was constructed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the example object is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the example object is not null and is not a Brush,
/// or if the destinationType isn't one of the valid destination types.
/// </exception>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call.
/// If this is null, then no namespace prefixes will be included.</param>
/// <param name="cultureInfo"> The CultureInfo which is respected when converting. </param>
/// <param name="value"> The PropertyPath to convert. </param>
/// <param name="destinationType">The type to which to convert the PropertyPath instance. </param>
public override object ConvertTo(ITypeDescriptorContext typeDescriptorContext,
CultureInfo cultureInfo,
object value,
Type destinationType)
{
if (null == value)
{
throw new ArgumentNullException("value");
}
if (null == destinationType)
{
throw new ArgumentNullException("destinationType");
}
if (destinationType != typeof(String))
{
throw new ArgumentException(SR.Get(SRID.CannotConvertType, typeof(PropertyPath), destinationType.FullName));
}
PropertyPath path = value as PropertyPath;
if (path == null)
{
throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(PropertyPath)), "value");
}
if (path.PathParameters.Count == 0)
{
// if the path didn't use paramaters, just write it out as it is
return path.Path;
}
else
{
// if the path used parameters, convert them to (NamespacePrefix:OwnerType.DependencyPropertyName) syntax
string originalPath = path.Path;
Collection<object> parameters = path.PathParameters;
XamlDesignerSerializationManager manager = typeDescriptorContext == null ?
null :
typeDescriptorContext.GetService(typeof(XamlDesignerSerializationManager)) as XamlDesignerSerializationManager;
ValueSerializer typeSerializer = null;
IValueSerializerContext serializerContext = null;
if (manager == null)
{
serializerContext = typeDescriptorContext as IValueSerializerContext;
if (serializerContext != null)
{
typeSerializer = ValueSerializer.GetSerializerFor(typeof(Type), serializerContext);
}
}
StringBuilder builder = new StringBuilder();
int start = 0;
for (int i=0; i<originalPath.Length; ++i)
{
// look for (n)
if (originalPath[i] == '(')
{
int j;
for (j=i+1; j<originalPath.Length; ++j)
{
if (originalPath[j] == ')')
break;
}
int index;
if (Int32.TryParse( originalPath.Substring(i+1, j-i-1),
NumberStyles.Integer,
TypeConverterHelper.InvariantEnglishUS.NumberFormat,
out index))
{
// found (n). Write out the path so far, including the opening (
builder.Append(originalPath.Substring(start, i-start+1));
object pathPart = parameters[index];
// get the owner type and name of the accessor
DependencyProperty dp;
PropertyInfo pi;
PropertyDescriptor pd;
DynamicObjectAccessor doa;
PropertyPath.DowncastAccessor(pathPart, out dp, out pi, out pd, out doa);
Type type; // the accessor's ownerType, or type of indexer parameter
string name; // the accessor's propertyName, or string value of indexer parameter
if (dp != null)
{
type = dp.OwnerType;
name = dp.Name;
}
else if (pi != null)
{
type = pi.DeclaringType;
name = pi.Name;
}
else if (pd != null)
{
type = pd.ComponentType;
name = pd.Name;
}
else if (doa != null)
{
type = doa.OwnerType;
name = doa.PropertyName;
}
else
{
// pathPart is an Indexer Parameter
type = pathPart.GetType();
name = null;
}
// write out the type of the accessor or index parameter
if (typeSerializer != null)
{
builder.Append(typeSerializer.ConvertToString(type, serializerContext));
}
else
{
//
string prefix = null;
if (prefix != null && prefix != string.Empty)
{
builder.Append(prefix);
builder.Append(':');
}
builder.Append(type.Name);
}
if (name != null)
{
// write out the accessor name
builder.Append('.');
builder.Append(name);
// write out the closing )
builder.Append(')');
}
else
{
// write out the ) that closes the parameter's type
builder.Append(')');
name = pathPart as string;
if (name == null)
{
// convert the parameter into string
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
{
try
{
name = converter.ConvertToString(pathPart);
}
catch (NotSupportedException)
{
}
}
}
// write out the parameter's value string
builder.Append(name);
}
// resume after the (n)
i = j;
start = j+1;
}
}
}
if (start < originalPath.Length)
{
builder.Append(originalPath.Substring(start));
}
return builder.ToString();
}
}
#endregion
}
}
| |
//
// 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 System.Globalization;
using System.IO;
using System.Text;
namespace Encog.Util.CSV
{
/// <summary>
/// Read and parse CSV format files.
/// </summary>
public class ReadCSV
{
/// <summary>
/// The names of the columns.
/// </summary>
private readonly IList<String> _columnNames = new List<String>();
/// <summary>
/// The names of the columns.
/// </summary>
private readonly IDictionary<String, int> _columns = new Dictionary<String, int>();
/// <summary>
/// The file to read.
/// </summary>
private readonly TextReader _reader;
/// <summary>
/// The data.
/// </summary>
private String[] _data;
/// <summary>
/// The delimiter.
/// </summary>
private char _delim;
/// <summary>
/// Used to parse the CSV.
/// </summary>
private ParseCSVLine parseLine;
/// <summary>
/// Construct a CSV reader from an input stream.
/// </summary>
/// <param name="istream">The InputStream to read from.</param>
/// <param name="headers">Are headers present?</param>
/// <param name="delim">What is the delimiter.</param>
public ReadCSV(Stream istream, bool headers,
char delim)
{
var format = new CSVFormat(CSVFormat.DecimalCharacter, delim);
_reader = new StreamReader(istream);
_delim = delim;
Begin(headers, format);
}
/// <summary>
/// Construct a CSV reader from a filename.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="headers">The headers.</param>
/// <param name="delim">The delimiter.</param>
public ReadCSV(String filename, bool headers,
char delim)
{
var format = new CSVFormat(CSVFormat.DecimalCharacter, delim);
_reader = new StreamReader(filename);
_delim = delim;
Begin(headers, format);
}
/// <summary>
/// Construct a CSV reader from a filename.
/// Allows a delimiter character to be specified.
/// Numbers will be parsed using the current
/// locale.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="headers">The headers.</param>
/// <param name="format">The delimiter.</param>
public ReadCSV(String filename, bool headers,
CSVFormat format)
{
_reader = new StreamReader(filename);
Begin(headers, format);
}
/// <summary>
/// Construct a CSV reader from an input stream.
/// The format parameter specifies the separator
/// character to use, as well as the number
/// format.
/// </summary>
/// <param name="stream">The Stream to read from.</param>
/// <param name="headers">Are headers present?</param>
/// <param name="format">What is the CSV format.</param>
public ReadCSV(Stream stream, bool headers,
CSVFormat format)
{
_reader = new StreamReader(stream);
Begin(headers, format);
}
/// <summary>
/// The format that dates are expected to be in. (i.e. "yyyy-MM-dd")
/// </summary>
public String DateFormat { get; set; }
/// <summary>
/// The format that times are expected to be in. (i.e. "hhmmss").
/// </summary>
public String TimeFormat { get; set; }
/// <summary>
/// The current format.
/// </summary>
public CSVFormat Format
{
get { return this.parseLine.Format; }
}
/// <summary>
/// The names of the columns.
/// </summary>
public IList<String> ColumnNames
{
get { return _columnNames; }
}
/// <summary>
/// Return the number of columns, if known.
/// </summary>
public int ColumnCount
{
get
{
if (_data == null)
{
return 0;
}
return _data.Length;
}
}
/// <summary>
/// Parse a date using the specified format.
/// </summary>
/// <param name="when">A string that contains a date in the specified format.</param>
/// <param name="dateFormat">The date format.</param>
/// <returns>A DateTime that was parsed.</returns>
public static DateTime ParseDate(String when, String dateFormat)
{
try
{
return DateTime.ParseExact(when, dateFormat,
CultureInfo.InvariantCulture);
}
catch (FormatException)
{
return default(DateTime);
}
}
/// <summary>
/// Read the headers.
/// </summary>
/// <param name="format">The format of this CSV file.</param>
/// <param name="headers">Are headers present.</param>
private void Begin(bool headers, CSVFormat format)
{
try
{
DateFormat = "yyyy-MM-dd";
TimeFormat = "HHmmss";
this.parseLine = new ParseCSVLine(format);
// read the column heads
if (headers)
{
String line = _reader.ReadLine();
IList<String> tok = parseLine.Parse(line);
int i = 0;
foreach (String header in tok)
{
if (_columns.ContainsKey(header.ToLower()))
throw new EncogError("Two columns cannot have the same name");
_columns.Add(header.ToLower(), i++);
_columnNames.Add(header);
}
}
_data = null;
}
catch (IOException e)
{
#if logging
if (logger.IsErrorEnabled)
{
logger.Error("Exception", e);
}
#endif
throw new EncogError(e);
}
}
/// <summary>
/// Close the file.
/// </summary>
public void Close()
{
try
{
_reader.Close();
}
catch (IOException e)
{
#if logging
if (logger.IsErrorEnabled)
{
logger.Error("Exception", e);
}
#endif
throw new EncogError(e);
}
}
/// <summary>
/// Get the specified column as a string.
/// </summary>
/// <param name="i">The column index, starting at zero.</param>
/// <returns>The column as a string.</returns>
public String Get(int i)
{
if( i>=_data.Length ) {
throw new EncogError("Can't access column " + i + " in a file that has only " + _data.Length + " columns.");
}
return _data[i];
}
/// <summary>
/// Get the column by its string name, as a string. This will only work if
/// column headers were defined that have string names.
/// </summary>
/// <param name="column">The column name.</param>
/// <returns>The column data as a string.</returns>
public String Get(String column)
{
if (!_columns.ContainsKey(column.ToLower()))
return null;
int i = _columns[column.ToLower()];
return _data[i];
}
/// <summary>
/// Get the column count.
/// </summary>
/// <returns>The column count.</returns>
public int GetCount()
{
if (_data == null)
{
return 0;
}
return _data.Length;
}
/// <summary>
/// Read the specified column as a date.
/// </summary>
/// <param name="column">The specified column.</param>
/// <returns>The specified column as a DateTime.</returns>
public DateTime GetDate(String column)
{
String str = Get(column);
return DateTime.ParseExact(str, DateFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Read the specified column as a time.
/// </summary>
/// <param name="column">The specified column.</param>
/// <returns>The specified column as a DateTime.</returns>
public DateTime GetTime(String column)
{
String str = Get(column);
return DateTime.ParseExact(str, TimeFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Read the specified column as a date.
/// </summary>
/// <param name="column">The specified column.</param>
/// <returns>The specified column as a DateTime.</returns>
public DateTime GetDate(int column)
{
String str = Get(column);
return DateTime.ParseExact(str, DateFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Read the specified column as a time.
/// </summary>
/// <param name="column">The specified column.</param>
/// <returns>The specified column as a DateTime.</returns>
public DateTime GetTime(int column)
{
String str = Get(column);
return DateTime.ParseExact(str, TimeFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Get the specified column as a double.
/// </summary>
/// <param name="column">The column to read.</param>
/// <returns>The specified column as a double.</returns>
public double GetDouble(String column)
{
String str = Get(column);
return parseLine.Format.Parse(str);
}
/// <summary>
/// Get the specified column as a double.
/// </summary>
/// <param name="column">The column to read.</param>
/// <returns>The specified column as a double.</returns>
public double GetDouble(int column)
{
String str = Get(column);
return parseLine.Format.Parse(str);
}
/// <summary>
/// Get an integer that has the specified name.
/// </summary>
/// <param name="col">The column name to read.</param>
/// <returns>The specified column as an int.</returns>
public int GetInt(String col)
{
String str = Get(col);
try
{
return int.Parse(str);
}
catch (FormatException)
{
return 0;
}
}
/// <summary>
/// Count the columns and create a an array to hold them.
/// </summary>
/// <param name="line">One line from the file</param>
private void InitData(string line)
{
IList<String> tok = parseLine.Parse(line);
_data = new String[tok.Count];
}
/// <summary>
/// Read the next line.
/// </summary>
/// <returns>True if there are more lines to read.</returns>
public bool Next()
{
try
{
String line;
do
{
line = _reader.ReadLine();
} while ((line != null) && line.Trim().Length == 0);
if (line == null)
{
return false;
}
if (_data == null)
{
InitData(line);
}
IList<String> tok = parseLine.Parse(line);
int i = 0;
foreach (String str in tok)
{
if (i < _data.Length)
{
_data[i++] = str;
}
}
return true;
}
catch (IOException e)
{
#if logging
if (logger.IsErrorEnabled)
{
logger.Error("Exception", e);
}
#endif
throw new EncogError(e);
}
}
internal long GetLong(int col)
{
String str = Get(col);
try
{
return long.Parse(str);
}
catch (FormatException)
{
return 0;
}
}
/// <summary>
/// Check to see if there are any missing values on the current row.
/// </summary>
/// <returns>True, if there are missing values.</returns>
public bool HasMissing()
{
for (int i = 0; i < _data.Length; i++)
{
String s = _data[i].Trim();
if (s.Length == 0 || s.Equals("?"))
{
return true;
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Xaml;
using System.Xaml.MS.Impl;
using System.Xaml.Schema;
using MS.Internal.Xaml.Context;
namespace MS.Internal.Xaml.Parser
{
// Markup Extension Tokenizer AKA Scanner.
enum MeTokenType
{
None,
Open = '{',
Close = '}',
EqualSign = '=',
Comma = ',',
TypeName, // String - Follows a '{' space delimited
PropertyName, // String - Preceeds a '='. {},= delimited, can (but shouldn't) contain spaces.
String, // String - all other strings, {},= delimited can contain spaces.
QuotedMarkupExtension // String - must be recursivly parsed as a MarkupExtension.
};
// 1) Value and (propertynames for compatibility with WPF 3.0) can also have
// escaped character with '\' to include '{' '}' ',' '=', and '\'.
// 2) Value strings can also be quoted (w/ ' or ") in their entirity to escape all
// uses of the above characters.
// 3) All strings are trimmed of whitespace front and back unless they were quoted.
// 4) Quote characters can only appear at the start and end of strings.
// 5) TypeNames cannot be quoted.
internal class MeScanner
{
public const char Space = ' ';
public const char OpenCurlie = '{';
public const char CloseCurlie = '}';
public const char Comma = ',';
public const char EqualSign = '=';
public const char Quote1 = '\'';
public const char Quote2 = '\"';
public const char Backslash = '\\';
public const char NullChar = '\0';
enum StringState { Value, Type, Property };
XamlParserContext _context;
string _inputText;
int _idx;
MeTokenType _token;
XamlType _tokenXamlType;
XamlMember _tokenProperty;
string _tokenNamespace;
string _tokenText;
StringState _state;
bool _hasTrailingWhitespace;
int _lineNumber;
int _startPosition;
private string _currentParameterName;
private SpecialBracketCharacters _currentSpecialBracketCharacters;
public MeScanner(XamlParserContext context, string text, int lineNumber, int linePosition)
{
_context = context;
_inputText = text;
_lineNumber = lineNumber;
_startPosition = linePosition;
_idx = -1;
_state = StringState.Value;
_currentParameterName = null;
_currentSpecialBracketCharacters = null;
}
public int LineNumber
{
get { return _lineNumber; }
}
public int LinePosition
{
get
{
int offset = (_idx < 0) ? 0 : _idx;
return _startPosition + offset;
}
}
public string Namespace
{
get { return _tokenNamespace; }
}
public MeTokenType Token
{
get { return _token; }
}
public XamlType TokenType
{
get { return _tokenXamlType; }
}
public XamlMember TokenProperty
{
get { return _tokenProperty; }
}
public string TokenText
{
get { return _tokenText; }
}
public bool IsAtEndOfInput
{
get { return (_idx >= _inputText.Length); }
}
public bool HasTrailingWhitespace
{
get { return _hasTrailingWhitespace; }
}
public void Read()
{
bool isQuotedMarkupExtension = false;
bool readString = false;
_tokenText = string.Empty;
_tokenXamlType = null;
_tokenProperty = null;
_tokenNamespace = null;
Advance();
AdvanceOverWhitespace();
if (IsAtEndOfInput)
{
_token = MeTokenType.None;
return;
}
switch (CurrentChar)
{
case OpenCurlie:
if (NextChar == CloseCurlie) // the {} escapes the ME. return the string.
{
_token = MeTokenType.String;
_state = StringState.Value;
readString = true; // ReadString() will strip the leading {}
}
else
{
_token = MeTokenType.Open;
_state = StringState.Type; // types follow '{'
}
break;
case Quote1:
case Quote2:
if (NextChar == OpenCurlie)
{
Advance(); // read ahead one character
if (NextChar != CloseCurlie) // check for the '}' of a {}
{
isQuotedMarkupExtension = true;
}
PushBack(); // put back the read-ahead.
}
readString = true; // read substring"
break;
case CloseCurlie:
_token = MeTokenType.Close;
_state = StringState.Value;
break;
case EqualSign:
_token = MeTokenType.EqualSign;
_state = StringState.Value;
_context.CurrentBracketModeParseParameters.IsConstructorParsingMode = false;
break;
case Comma:
_token = MeTokenType.Comma;
_state = StringState.Value;
if (_context.CurrentBracketModeParseParameters.IsConstructorParsingMode)
{
_context.CurrentBracketModeParseParameters.IsConstructorParsingMode =
++_context.CurrentBracketModeParseParameters.CurrentConstructorParam <
_context.CurrentBracketModeParseParameters.MaxConstructorParams;
}
break;
default:
readString = true;
break;
}
if(readString)
{
if (_context.CurrentType.IsMarkupExtension
&& _context.CurrentBracketModeParseParameters != null
&& _context.CurrentBracketModeParseParameters.IsConstructorParsingMode)
{
int currentCtrParam = _context.CurrentBracketModeParseParameters.CurrentConstructorParam;
_currentParameterName = _context.CurrentLongestConstructorOfMarkupExtension[currentCtrParam].Name;
_currentSpecialBracketCharacters = GetBracketCharacterForProperty(_currentParameterName);
}
string str = ReadString();
_token = (isQuotedMarkupExtension) ? MeTokenType.QuotedMarkupExtension : MeTokenType.String;
switch (_state)
{
case StringState.Value:
break;
case StringState.Type:
_token = MeTokenType.TypeName;
ResolveTypeName(str);
break;
case StringState.Property:
_token = MeTokenType.PropertyName;
ResolvePropertyName(str);
break;
}
_state = StringState.Value;
_tokenText = RemoveEscapes(str);
}
}
private static string RemoveEscapes(string value)
{
if (value.StartsWith("{}", StringComparison.OrdinalIgnoreCase))
{
value = value.Substring(2);
}
if (!value.Contains("\\"))
{
return value;
}
StringBuilder builder = new StringBuilder(value.Length);
int start = 0;
int idx;
do
{
idx = value.IndexOf(Backslash, start);
if (idx < 0)
{
builder.Append(value, start, value.Length - start);
break;
}
else
{
int clearTextLength = idx - start;
// Copy Clear Text
builder.Append(value, start, clearTextLength);
// Add the character after the backslash
if (idx + 1 < value.Length)
{
builder.Append(value[idx + 1]);
}
// pick up again after that
start = idx + 2;
}
} while (start < value.Length);
string result = builder.ToString();
return result;
}
private void ResolveTypeName(string longName)
{
string error;
XamlTypeName typeName = XamlTypeName.ParseInternal(longName, _context.FindNamespaceByPrefix, out error);
if (typeName == null)
{
throw new XamlParseException(this, error);
}
// In curly form, we search for TypeName + 'Extension' before TypeName
string bareTypeName = typeName.Name;
typeName.Name = typeName.Name + KnownStrings.Extension;
XamlType xamlType = _context.GetXamlType(typeName, false);
// This would be cleaner if we moved the Extension fallback logic out of XSC
if (xamlType == null ||
// Guard against Extension getting added twice
(xamlType.UnderlyingType != null &&
KS.Eq(xamlType.UnderlyingType.Name, typeName.Name + KnownStrings.Extension)))
{
typeName.Name = bareTypeName;
xamlType = _context.GetXamlType(typeName, true);
}
_tokenXamlType = xamlType;
_tokenNamespace = typeName.Namespace;
}
private void ResolvePropertyName(string longName)
{
XamlPropertyName propName = XamlPropertyName.Parse(longName);
if (propName == null)
{
throw new ArgumentException(SR.Get(SRID.MalformedPropertyName));
}
XamlMember prop = null;
XamlType declaringType;
XamlType tagType = _context.CurrentType;
string tagNamespace = _context.CurrentTypeNamespace;
if (propName.IsDotted)
{
prop = _context.GetDottedProperty(tagType, tagNamespace, propName, false /*tagIsRoot*/);
}
// Regular property p
else
{
string ns = _context.GetAttributeNamespace(propName, Namespace);
declaringType = _context.CurrentType;
prop = _context.GetNoDotAttributeProperty(declaringType, propName, Namespace, ns, false /*tagIsRoot*/);
}
_tokenProperty = prop;
}
private string ReadString()
{
bool escaped = false;
char quoteChar = NullChar;
bool atStart = true;
bool wasQuoted = false;
uint braceCount = 0; // To be compat with v3 which allowed balanced {} inside of strings
StringBuilder sb = new StringBuilder();
char ch;
while(!IsAtEndOfInput)
{
ch = CurrentChar;
// handle escaping and quoting first.
if(escaped)
{
sb.Append('\\');
sb.Append(ch);
escaped = false;
}
else if (quoteChar != NullChar)
{
if (ch == Backslash)
{
escaped = true;
}
else if (ch != quoteChar)
{
sb.Append(ch);
}
else
{
ch = CurrentChar;
quoteChar = NullChar;
break; // we are done.
}
}
// If we are inside of MarkupExtensionBracketCharacters for a particular property or position parameter,
// scoop up everything inside one by one, and keep track of nested Bracket Characters in the stack.
else if (_context.CurrentBracketModeParseParameters != null && _context.CurrentBracketModeParseParameters.IsBracketEscapeMode)
{
Stack<char> bracketCharacterStack = _context.CurrentBracketModeParseParameters.BracketCharacterStack;
if (_currentSpecialBracketCharacters.StartsEscapeSequence(ch))
{
bracketCharacterStack.Push(ch);
}
else if (_currentSpecialBracketCharacters.EndsEscapeSequence(ch))
{
if (_currentSpecialBracketCharacters.Match(bracketCharacterStack.Peek(), ch))
{
bracketCharacterStack.Pop();
}
else
{
throw new XamlParseException(this, SR.Get(SRID.InvalidClosingBracketCharacers, ch.ToString()));
}
}
else if (ch == Backslash)
{
escaped = true;
}
if (bracketCharacterStack.Count == 0)
{
_context.CurrentBracketModeParseParameters.IsBracketEscapeMode = false;
}
if (!escaped)
{
sb.Append(ch);
}
}
else
{
bool done = false;
switch (ch)
{
case Space:
if (_state == StringState.Type)
{
done = true; // we are done.
break;
}
sb.Append(ch);
break;
case OpenCurlie:
braceCount++;
sb.Append(ch);
break;
case CloseCurlie:
if (braceCount == 0)
{
done = true;
}
else
{
braceCount--;
sb.Append(ch);
}
break;
case Comma:
done = true; // we are done.
break;
case EqualSign:
_state = StringState.Property;
done = true; // we are done.
break;
case Backslash:
escaped = true;
break;
case Quote1:
case Quote2:
if (!atStart)
{
throw new XamlParseException(this, SR.Get(SRID.QuoteCharactersOutOfPlace));
}
quoteChar = ch;
wasQuoted = true;
break;
default: // All other character (including whitespace)
if (_currentSpecialBracketCharacters != null && _currentSpecialBracketCharacters.StartsEscapeSequence(ch))
{
Stack<char> bracketCharacterStack =
_context.CurrentBracketModeParseParameters.BracketCharacterStack;
bracketCharacterStack.Clear();
bracketCharacterStack.Push(ch);
_context.CurrentBracketModeParseParameters.IsBracketEscapeMode = true;
}
sb.Append(ch);
break;
}
if (done)
{
if (braceCount > 0)
{
throw new XamlParseException(this, SR.Get(SRID.UnexpectedTokenAfterME));
}
else
{
if (_context.CurrentBracketModeParseParameters?.BracketCharacterStack.Count > 0)
{
throw new XamlParseException(this, SR.Get(SRID.MalformedBracketCharacters, ch.ToString()));
}
}
PushBack();
break; // we are done.
}
}
atStart = false;
Advance();
}
if (quoteChar != NullChar)
{
throw new XamlParseException(this, SR.Get(SRID.UnclosedQuote));
}
string result = sb.ToString();
if (!wasQuoted)
{
result = result.TrimEnd(KnownStrings.WhitespaceChars);
result = result.TrimStart(KnownStrings.WhitespaceChars);
}
if (_state == StringState.Property)
{
_currentParameterName = result;
_currentSpecialBracketCharacters = GetBracketCharacterForProperty(_currentParameterName);
}
return result;
}
private char CurrentChar
{
get { return _inputText[_idx]; }
}
private char NextChar
{
get
{
if (_idx + 1 < _inputText.Length)
{
return _inputText[_idx + 1];
}
return NullChar;
}
}
private bool Advance()
{
++_idx;
if (IsAtEndOfInput)
{
_idx = _inputText.Length;
return false;
}
return true;
}
private static bool IsWhitespaceChar(char ch)
{
Debug.Assert(KnownStrings.WhitespaceChars.Length == 5);
if (ch == KnownStrings.WhitespaceChars[0] ||
ch == KnownStrings.WhitespaceChars[1] ||
ch == KnownStrings.WhitespaceChars[2] ||
ch == KnownStrings.WhitespaceChars[3] ||
ch == KnownStrings.WhitespaceChars[4])
{
return true;
}
return false;
}
private void AdvanceOverWhitespace()
{
bool sawWhitespace = false;
while (!IsAtEndOfInput && IsWhitespaceChar(CurrentChar))
{
sawWhitespace = true;
Advance();
}
// WFP 3.0 errors on trailing whitespace.
// [note: very first compat workaround in the new XAML parser]
// Noticing trailing whitespace is not very natural in this parser.
// so this extra code is here to implement this error.
if (IsAtEndOfInput && sawWhitespace)
{
_hasTrailingWhitespace = true;
}
}
private void PushBack()
{
_idx -= 1;
}
private SpecialBracketCharacters GetBracketCharacterForProperty(string propertyName)
{
SpecialBracketCharacters bracketCharacters = null;
if (_context.CurrentEscapeCharacterMapForMarkupExtension != null &&
_context.CurrentEscapeCharacterMapForMarkupExtension.ContainsKey(propertyName))
{
bracketCharacters = _context.CurrentEscapeCharacterMapForMarkupExtension[propertyName];
}
return bracketCharacters;
}
}
internal class BracketModeParseParameters
{
internal BracketModeParseParameters(XamlParserContext context)
{
CurrentConstructorParam = 0;
IsBracketEscapeMode = false;
BracketCharacterStack = new Stack<char>();
if (context.CurrentLongestConstructorOfMarkupExtension != null)
{
IsConstructorParsingMode = context.CurrentLongestConstructorOfMarkupExtension.Length > 0;
MaxConstructorParams = context.CurrentLongestConstructorOfMarkupExtension.Length;
}
else
{
IsConstructorParsingMode = false;
MaxConstructorParams = 0;
}
}
internal int CurrentConstructorParam { get; set; }
internal int MaxConstructorParams { get; set; }
internal bool IsConstructorParsingMode { get; set; }
internal bool IsBracketEscapeMode { get; set; }
internal Stack<char> BracketCharacterStack { 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.
using System;
using Internal.TypeSystem;
using Internal.IL;
namespace Internal.IL
{
//
// Corresponds to "I.12.3.2.1 The evaluation stack" in ECMA spec
//
internal enum StackValueKind
{
/// <summary>An unknow type.</summary>
Unknown,
/// <summary>Any signed or unsigned integer values that can be represented as a 32-bit entity.</summary>
Int32,
/// <summary>Any signed or unsigned integer values that can be represented as a 64-bit entity.</summary>
Int64,
/// <summary>Underlying platform pointer type represented as an integer of the appropriate size.</summary>
NativeInt,
/// <summary>Any float value.</summary>
Float,
/// <summary>A managed pointer.</summary>
ByRef,
/// <summary>An object reference.</summary>
ObjRef,
/// <summary>A value type which is not any of the primitive one.</summary>
ValueType
}
internal partial class ILImporter
{
private BasicBlock[] _basicBlocks; // Maps IL offset to basic block
private BasicBlock _currentBasicBlock;
private int _currentOffset;
private BasicBlock _pendingBasicBlocks;
//
// IL stream reading
//
private byte ReadILByte()
{
return _ilBytes[_currentOffset++];
}
private UInt16 ReadILUInt16()
{
UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8));
_currentOffset += 2;
return val;
}
private UInt32 ReadILUInt32()
{
UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24));
_currentOffset += 4;
return val;
}
private int ReadILToken()
{
return (int)ReadILUInt32();
}
private ulong ReadILUInt64()
{
ulong value = ReadILUInt32();
value |= (((ulong)ReadILUInt32()) << 32);
return value;
}
private unsafe float ReadILFloat()
{
uint value = ReadILUInt32();
return *(float*)(&value);
}
private unsafe double ReadILDouble()
{
ulong value = ReadILUInt64();
return *(double*)(&value);
}
private void SkipIL(int bytes)
{
_currentOffset += bytes;
}
//
// Basic block identification
//
private void FindBasicBlocks()
{
_basicBlocks = new BasicBlock[_ilBytes.Length];
CreateBasicBlock(0);
FindJumpTargets();
FindEHTargets();
}
private BasicBlock CreateBasicBlock(int offset)
{
BasicBlock basicBlock = _basicBlocks[offset];
if (basicBlock == null)
{
basicBlock = new BasicBlock() { StartOffset = offset };
_basicBlocks[offset] = basicBlock;
}
return basicBlock;
}
private void FindJumpTargets()
{
_currentOffset = 0;
while (_currentOffset < _ilBytes.Length)
{
MarkInstructionBoundary();
ILOpcode opCode = (ILOpcode)ReadILByte();
again:
switch (opCode)
{
case ILOpcode.ldarg_s:
case ILOpcode.ldarga_s:
case ILOpcode.starg_s:
case ILOpcode.ldloc_s:
case ILOpcode.ldloca_s:
case ILOpcode.stloc_s:
case ILOpcode.ldc_i4_s:
case ILOpcode.unaligned:
SkipIL(1);
break;
case ILOpcode.ldarg:
case ILOpcode.ldarga:
case ILOpcode.starg:
case ILOpcode.ldloc:
case ILOpcode.ldloca:
case ILOpcode.stloc:
SkipIL(2);
break;
case ILOpcode.ldc_i4:
case ILOpcode.ldc_r4:
SkipIL(4);
break;
case ILOpcode.ldc_i8:
case ILOpcode.ldc_r8:
SkipIL(8);
break;
case ILOpcode.jmp:
case ILOpcode.call:
case ILOpcode.calli:
case ILOpcode.callvirt:
case ILOpcode.cpobj:
case ILOpcode.ldobj:
case ILOpcode.ldstr:
case ILOpcode.newobj:
case ILOpcode.castclass:
case ILOpcode.isinst:
case ILOpcode.unbox:
case ILOpcode.ldfld:
case ILOpcode.ldflda:
case ILOpcode.stfld:
case ILOpcode.ldsfld:
case ILOpcode.ldsflda:
case ILOpcode.stsfld:
case ILOpcode.stobj:
case ILOpcode.box:
case ILOpcode.newarr:
case ILOpcode.ldelema:
case ILOpcode.ldelem:
case ILOpcode.stelem:
case ILOpcode.unbox_any:
case ILOpcode.refanyval:
case ILOpcode.mkrefany:
case ILOpcode.ldtoken:
case ILOpcode.ldftn:
case ILOpcode.ldvirtftn:
case ILOpcode.initobj:
case ILOpcode.constrained:
case ILOpcode.sizeof_:
SkipIL(4);
break;
case ILOpcode.prefix1:
opCode = (ILOpcode)(0x100 + ReadILByte());
goto again;
case ILOpcode.br_s:
case ILOpcode.leave_s:
{
int delta = (sbyte)ReadILByte();
int target = _currentOffset + delta;
if ((uint)target < (uint)_basicBlocks.Length)
CreateBasicBlock(target);
else
ReportInvalidBranchTarget(target);
}
break;
case ILOpcode.brfalse_s:
case ILOpcode.brtrue_s:
case ILOpcode.beq_s:
case ILOpcode.bge_s:
case ILOpcode.bgt_s:
case ILOpcode.ble_s:
case ILOpcode.blt_s:
case ILOpcode.bne_un_s:
case ILOpcode.bge_un_s:
case ILOpcode.bgt_un_s:
case ILOpcode.ble_un_s:
case ILOpcode.blt_un_s:
{
int delta = (sbyte)ReadILByte();
int target = _currentOffset + delta;
if ((uint)target < (uint)_basicBlocks.Length)
CreateBasicBlock(target);
else
ReportInvalidBranchTarget(target);
CreateBasicBlock(_currentOffset);
}
break;
case ILOpcode.br:
case ILOpcode.leave:
{
int delta = (int)ReadILUInt32();
int target = _currentOffset + delta;
if ((uint)target < (uint)_basicBlocks.Length)
CreateBasicBlock(target);
else
ReportInvalidBranchTarget(target);
}
break;
case ILOpcode.brfalse:
case ILOpcode.brtrue:
case ILOpcode.beq:
case ILOpcode.bge:
case ILOpcode.bgt:
case ILOpcode.ble:
case ILOpcode.blt:
case ILOpcode.bne_un:
case ILOpcode.bge_un:
case ILOpcode.bgt_un:
case ILOpcode.ble_un:
case ILOpcode.blt_un:
{
int delta = (int)ReadILUInt32();
int target = _currentOffset + delta;
if ((uint)target < (uint)_basicBlocks.Length)
CreateBasicBlock(target);
else
ReportInvalidBranchTarget(target);
CreateBasicBlock(_currentOffset);
}
break;
case ILOpcode.switch_:
{
uint count = ReadILUInt32();
int jmpBase = _currentOffset + (int)(4 * count);
for (uint i = 0; i < count; i++)
{
int delta = (int)ReadILUInt32();
int target = jmpBase + delta;
if ((uint)target < (uint)_basicBlocks.Length)
CreateBasicBlock(target);
else
ReportInvalidBranchTarget(target);
}
CreateBasicBlock(_currentOffset);
}
break;
default:
continue;
}
}
}
private void FindEHTargets()
{
for (int i = 0; i < _exceptionRegions.Length; i++)
{
var r = _exceptionRegions[i];
CreateBasicBlock(r.ILRegion.TryOffset).TryStart = true;
if (r.ILRegion.Kind == ILExceptionRegionKind.Filter)
CreateBasicBlock(r.ILRegion.FilterOffset).FilterStart = true;
CreateBasicBlock(r.ILRegion.HandlerOffset).HandlerStart = true;
}
}
//
// Basic block importing
//
private void ImportBasicBlocks()
{
_pendingBasicBlocks = _basicBlocks[0];
while (_pendingBasicBlocks != null)
{
BasicBlock basicBlock = _pendingBasicBlocks;
_pendingBasicBlocks = basicBlock.Next;
StartImportingBasicBlock(basicBlock);
ImportBasicBlock(basicBlock);
EndImportingBasicBlock(basicBlock);
}
}
private void MarkBasicBlock(BasicBlock basicBlock)
{
if (basicBlock.State == BasicBlock.ImportState.Unmarked)
{
// Link
basicBlock.Next = _pendingBasicBlocks;
_pendingBasicBlocks = basicBlock;
basicBlock.State = BasicBlock.ImportState.IsPending;
}
}
private void ImportBasicBlock(BasicBlock basicBlock)
{
_currentBasicBlock = basicBlock;
_currentOffset = basicBlock.StartOffset;
for (;;)
{
StartImportingInstruction();
ILOpcode opCode = (ILOpcode)ReadILByte();
again:
switch (opCode)
{
case ILOpcode.nop:
ImportNop();
break;
case ILOpcode.break_:
ImportBreak();
break;
case ILOpcode.ldarg_0:
case ILOpcode.ldarg_1:
case ILOpcode.ldarg_2:
case ILOpcode.ldarg_3:
ImportLoadVar(opCode - ILOpcode.ldarg_0, true);
break;
case ILOpcode.ldloc_0:
case ILOpcode.ldloc_1:
case ILOpcode.ldloc_2:
case ILOpcode.ldloc_3:
ImportLoadVar(opCode - ILOpcode.ldloc_0, false);
break;
case ILOpcode.stloc_0:
case ILOpcode.stloc_1:
case ILOpcode.stloc_2:
case ILOpcode.stloc_3:
ImportStoreVar(opCode - ILOpcode.stloc_0, false);
break;
case ILOpcode.ldarg_s:
ImportLoadVar(ReadILByte(), true);
break;
case ILOpcode.ldarga_s:
ImportAddressOfVar(ReadILByte(), true);
break;
case ILOpcode.starg_s:
ImportStoreVar(ReadILByte(), true);
break;
case ILOpcode.ldloc_s:
ImportLoadVar(ReadILByte(), false);
break;
case ILOpcode.ldloca_s:
ImportAddressOfVar(ReadILByte(), false);
break;
case ILOpcode.stloc_s:
ImportStoreVar(ReadILByte(), false);
break;
case ILOpcode.ldnull:
ImportLoadNull();
break;
case ILOpcode.ldc_i4_m1:
ImportLoadInt(-1, StackValueKind.Int32);
break;
case ILOpcode.ldc_i4_0:
case ILOpcode.ldc_i4_1:
case ILOpcode.ldc_i4_2:
case ILOpcode.ldc_i4_3:
case ILOpcode.ldc_i4_4:
case ILOpcode.ldc_i4_5:
case ILOpcode.ldc_i4_6:
case ILOpcode.ldc_i4_7:
case ILOpcode.ldc_i4_8:
ImportLoadInt(opCode - ILOpcode.ldc_i4_0, StackValueKind.Int32);
break;
case ILOpcode.ldc_i4_s:
ImportLoadInt((sbyte)ReadILByte(), StackValueKind.Int32);
break;
case ILOpcode.ldc_i4:
ImportLoadInt((int)ReadILUInt32(), StackValueKind.Int32);
break;
case ILOpcode.ldc_i8:
ImportLoadInt((long)ReadILUInt64(), StackValueKind.Int64);
break;
case ILOpcode.ldc_r4:
ImportLoadFloat(ReadILFloat());
break;
case ILOpcode.ldc_r8:
ImportLoadFloat(ReadILDouble());
break;
case ILOpcode.dup:
ImportDup();
break;
case ILOpcode.pop:
ImportPop();
break;
case ILOpcode.jmp:
ImportJmp(ReadILToken());
return;
case ILOpcode.call:
ImportCall(opCode, ReadILToken());
break;
case ILOpcode.calli:
ImportCalli(ReadILToken());
break;
case ILOpcode.ret:
ImportReturn();
return;
case ILOpcode.br_s:
case ILOpcode.brfalse_s:
case ILOpcode.brtrue_s:
case ILOpcode.beq_s:
case ILOpcode.bge_s:
case ILOpcode.bgt_s:
case ILOpcode.ble_s:
case ILOpcode.blt_s:
case ILOpcode.bne_un_s:
case ILOpcode.bge_un_s:
case ILOpcode.bgt_un_s:
case ILOpcode.ble_un_s:
case ILOpcode.blt_un_s:
{
int delta = (sbyte)ReadILByte();
ImportBranch(opCode + (ILOpcode.br - ILOpcode.br_s),
_basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br_s) ? _basicBlocks[_currentOffset] : null);
}
return;
case ILOpcode.br:
case ILOpcode.brfalse:
case ILOpcode.brtrue:
case ILOpcode.beq:
case ILOpcode.bge:
case ILOpcode.bgt:
case ILOpcode.ble:
case ILOpcode.blt:
case ILOpcode.bne_un:
case ILOpcode.bge_un:
case ILOpcode.bgt_un:
case ILOpcode.ble_un:
case ILOpcode.blt_un:
{
int delta = (int)ReadILUInt32();
ImportBranch(opCode,
_basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br) ? _basicBlocks[_currentOffset] : null);
}
return;
case ILOpcode.switch_:
{
uint count = ReadILUInt32();
int jmpBase = _currentOffset + (int)(4 * count);
int[] jmpDelta = new int[count];
for (uint i = 0; i < count; i++)
jmpDelta[i] = (int)ReadILUInt32();
ImportSwitchJump(jmpBase, jmpDelta, _basicBlocks[_currentOffset]);
}
return;
case ILOpcode.ldind_i1:
ImportLoadIndirect(WellKnownType.SByte);
break;
case ILOpcode.ldind_u1:
ImportLoadIndirect(WellKnownType.Byte);
break;
case ILOpcode.ldind_i2:
ImportLoadIndirect(WellKnownType.Int16);
break;
case ILOpcode.ldind_u2:
ImportLoadIndirect(WellKnownType.UInt16);
break;
case ILOpcode.ldind_i4:
ImportLoadIndirect(WellKnownType.Int32);
break;
case ILOpcode.ldind_u4:
ImportLoadIndirect(WellKnownType.UInt32);
break;
case ILOpcode.ldind_i8:
ImportLoadIndirect(WellKnownType.Int64);
break;
case ILOpcode.ldind_i:
ImportLoadIndirect(WellKnownType.IntPtr);
break;
case ILOpcode.ldind_r4:
ImportLoadIndirect(WellKnownType.Single);
break;
case ILOpcode.ldind_r8:
ImportLoadIndirect(WellKnownType.Double);
break;
case ILOpcode.ldind_ref:
ImportLoadIndirect(null);
break;
case ILOpcode.stind_ref:
ImportStoreIndirect(null);
break;
case ILOpcode.stind_i1:
ImportStoreIndirect(WellKnownType.SByte);
break;
case ILOpcode.stind_i2:
ImportStoreIndirect(WellKnownType.Int16);
break;
case ILOpcode.stind_i4:
ImportStoreIndirect(WellKnownType.Int32);
break;
case ILOpcode.stind_i8:
ImportStoreIndirect(WellKnownType.Int64);
break;
case ILOpcode.stind_r4:
ImportStoreIndirect(WellKnownType.Single);
break;
case ILOpcode.stind_r8:
ImportStoreIndirect(WellKnownType.Double);
break;
case ILOpcode.add:
case ILOpcode.sub:
case ILOpcode.mul:
case ILOpcode.div:
case ILOpcode.div_un:
case ILOpcode.rem:
case ILOpcode.rem_un:
case ILOpcode.and:
case ILOpcode.or:
case ILOpcode.xor:
ImportBinaryOperation(opCode);
break;
case ILOpcode.shl:
case ILOpcode.shr:
case ILOpcode.shr_un:
ImportShiftOperation(opCode);
break;
case ILOpcode.neg:
case ILOpcode.not:
ImportUnaryOperation(opCode);
break;
case ILOpcode.conv_i1:
ImportConvert(WellKnownType.Byte, false, false);
break;
case ILOpcode.conv_i2:
ImportConvert(WellKnownType.Int16, false, false);
break;
case ILOpcode.conv_i4:
ImportConvert(WellKnownType.Int32, false, false);
break;
case ILOpcode.conv_i8:
ImportConvert(WellKnownType.Int64, false, false);
break;
case ILOpcode.conv_r4:
ImportConvert(WellKnownType.Single, false, false);
break;
case ILOpcode.conv_r8:
ImportConvert(WellKnownType.Double, false, false);
break;
case ILOpcode.conv_u4:
ImportConvert(WellKnownType.UInt32, false, false);
break;
case ILOpcode.conv_u8:
ImportConvert(WellKnownType.UInt64, false, false);
break;
case ILOpcode.callvirt:
ImportCall(opCode, ReadILToken());
break;
case ILOpcode.cpobj:
ImportCpOpj(ReadILToken());
break;
case ILOpcode.ldobj:
ImportLoadIndirect(ReadILToken());
break;
case ILOpcode.ldstr:
ImportLoadString(ReadILToken());
break;
case ILOpcode.newobj:
ImportCall(opCode, ReadILToken());
break;
case ILOpcode.castclass:
case ILOpcode.isinst:
ImportCasting(opCode, ReadILToken());
break;
case ILOpcode.conv_r_un:
ImportConvert(WellKnownType.Double, false, true);
break;
case ILOpcode.unbox:
ImportUnbox(ReadILToken(), opCode);
break;
case ILOpcode.throw_:
ImportThrow();
return;
case ILOpcode.ldfld:
ImportLoadField(ReadILToken(), false);
break;
case ILOpcode.ldflda:
ImportAddressOfField(ReadILToken(), false);
break;
case ILOpcode.stfld:
ImportStoreField(ReadILToken(), false);
break;
case ILOpcode.ldsfld:
ImportLoadField(ReadILToken(), true);
break;
case ILOpcode.ldsflda:
ImportAddressOfField(ReadILToken(), true);
break;
case ILOpcode.stsfld:
ImportStoreField(ReadILToken(), true);
break;
case ILOpcode.stobj:
ImportStoreIndirect(ReadILToken());
break;
case ILOpcode.conv_ovf_i1_un:
ImportConvert(WellKnownType.SByte, true, true);
break;
case ILOpcode.conv_ovf_i2_un:
ImportConvert(WellKnownType.Int16, true, true);
break;
case ILOpcode.conv_ovf_i4_un:
ImportConvert(WellKnownType.Int32, true, true);
break;
case ILOpcode.conv_ovf_i8_un:
ImportConvert(WellKnownType.Int64, true, true);
break;
case ILOpcode.conv_ovf_u1_un:
ImportConvert(WellKnownType.Byte, true, true);
break;
case ILOpcode.conv_ovf_u2_un:
ImportConvert(WellKnownType.UInt16, true, true);
break;
case ILOpcode.conv_ovf_u4_un:
ImportConvert(WellKnownType.UInt32, true, true);
break;
case ILOpcode.conv_ovf_u8_un:
ImportConvert(WellKnownType.UInt64, true, true);
break;
case ILOpcode.conv_ovf_i_un:
ImportConvert(WellKnownType.IntPtr, true, true);
break;
case ILOpcode.conv_ovf_u_un:
ImportConvert(WellKnownType.UIntPtr, true, true);
break;
case ILOpcode.box:
ImportBox(ReadILToken());
break;
case ILOpcode.newarr:
ImportNewArray(ReadILToken());
break;
case ILOpcode.ldlen:
ImportLoadLength();
break;
case ILOpcode.ldelema:
ImportAddressOfElement(ReadILToken());
break;
case ILOpcode.ldelem_i1:
ImportLoadElement(WellKnownType.SByte);
break;
case ILOpcode.ldelem_u1:
ImportLoadElement(WellKnownType.Byte);
break;
case ILOpcode.ldelem_i2:
ImportLoadElement(WellKnownType.Int16);
break;
case ILOpcode.ldelem_u2:
ImportLoadElement(WellKnownType.UInt16);
break;
case ILOpcode.ldelem_i4:
ImportLoadElement(WellKnownType.Int32);
break;
case ILOpcode.ldelem_u4:
ImportLoadElement(WellKnownType.UInt32);
break;
case ILOpcode.ldelem_i8:
ImportLoadElement(WellKnownType.Int64);
break;
case ILOpcode.ldelem_i:
ImportLoadElement(WellKnownType.IntPtr);
break;
case ILOpcode.ldelem_r4:
ImportLoadElement(WellKnownType.Single);
break;
case ILOpcode.ldelem_r8:
ImportLoadElement(WellKnownType.Double);
break;
case ILOpcode.ldelem_ref:
ImportLoadElement(null);
break;
case ILOpcode.stelem_i:
ImportStoreElement(WellKnownType.IntPtr);
break;
case ILOpcode.stelem_i1:
ImportStoreElement(WellKnownType.SByte);
break;
case ILOpcode.stelem_i2:
ImportStoreElement(WellKnownType.Int16);
break;
case ILOpcode.stelem_i4:
ImportStoreElement(WellKnownType.Int32);
break;
case ILOpcode.stelem_i8:
ImportStoreElement(WellKnownType.Int64);
break;
case ILOpcode.stelem_r4:
ImportStoreElement(WellKnownType.Single);
break;
case ILOpcode.stelem_r8:
ImportStoreElement(WellKnownType.Double);
break;
case ILOpcode.stelem_ref:
ImportStoreElement(null);
break;
case ILOpcode.ldelem:
ImportLoadElement(ReadILToken());
break;
case ILOpcode.stelem:
ImportStoreElement(ReadILToken());
break;
case ILOpcode.unbox_any:
ImportUnbox(ReadILToken(), opCode);
break;
case ILOpcode.conv_ovf_i1:
ImportConvert(WellKnownType.SByte, true, false);
break;
case ILOpcode.conv_ovf_u1:
ImportConvert(WellKnownType.Byte, true, false);
break;
case ILOpcode.conv_ovf_i2:
ImportConvert(WellKnownType.Int16, true, false);
break;
case ILOpcode.conv_ovf_u2:
ImportConvert(WellKnownType.UInt16, true, false);
break;
case ILOpcode.conv_ovf_i4:
ImportConvert(WellKnownType.Int32, true, false);
break;
case ILOpcode.conv_ovf_u4:
ImportConvert(WellKnownType.UInt32, true, false);
break;
case ILOpcode.conv_ovf_i8:
ImportConvert(WellKnownType.Int64, true, false);
break;
case ILOpcode.conv_ovf_u8:
ImportConvert(WellKnownType.UInt64, true, false);
break;
case ILOpcode.refanyval:
ImportRefAnyVal(ReadILToken());
break;
case ILOpcode.ckfinite:
ImportCkFinite();
break;
case ILOpcode.mkrefany:
ImportMkRefAny(ReadILToken());
break;
case ILOpcode.ldtoken:
ImportLdToken(ReadILToken());
break;
case ILOpcode.conv_u2:
ImportConvert(WellKnownType.UInt16, false, false);
break;
case ILOpcode.conv_u1:
ImportConvert(WellKnownType.Byte, false, false);
break;
case ILOpcode.conv_i:
ImportConvert(WellKnownType.IntPtr, false, false);
break;
case ILOpcode.conv_ovf_i:
ImportConvert(WellKnownType.IntPtr, true, false);
break;
case ILOpcode.conv_ovf_u:
ImportConvert(WellKnownType.UIntPtr, true, false);
break;
case ILOpcode.add_ovf:
case ILOpcode.add_ovf_un:
case ILOpcode.mul_ovf:
case ILOpcode.mul_ovf_un:
case ILOpcode.sub_ovf:
case ILOpcode.sub_ovf_un:
ImportBinaryOperation(opCode);
break;
case ILOpcode.endfinally: //both endfinally and endfault
ImportEndFinally();
return;
case ILOpcode.leave:
{
int delta = (int)ReadILUInt32();
ImportLeave(_basicBlocks[_currentOffset + delta]);
}
return;
case ILOpcode.leave_s:
{
int delta = (sbyte)ReadILByte();
ImportLeave(_basicBlocks[_currentOffset + delta]);
}
return;
case ILOpcode.stind_i:
ImportStoreIndirect(WellKnownType.IntPtr);
break;
case ILOpcode.conv_u:
ImportConvert(WellKnownType.UIntPtr, false, false);
break;
case ILOpcode.prefix1:
opCode = (ILOpcode)(0x100 + ReadILByte());
goto again;
case ILOpcode.arglist:
ImportArgList();
break;
case ILOpcode.ceq:
case ILOpcode.cgt:
case ILOpcode.cgt_un:
case ILOpcode.clt:
case ILOpcode.clt_un:
ImportCompareOperation(opCode);
break;
case ILOpcode.ldftn:
case ILOpcode.ldvirtftn:
ImportLdFtn(ReadILToken(), opCode);
break;
case ILOpcode.ldarg:
ImportLoadVar(ReadILUInt16(), true);
break;
case ILOpcode.ldarga:
ImportAddressOfVar(ReadILUInt16(), true);
break;
case ILOpcode.starg:
ImportStoreVar(ReadILUInt16(), true);
break;
case ILOpcode.ldloc:
ImportLoadVar(ReadILUInt16(), false);
break;
case ILOpcode.ldloca:
ImportAddressOfVar(ReadILUInt16(), false);
break;
case ILOpcode.stloc:
ImportStoreVar(ReadILUInt16(), false);
break;
case ILOpcode.localloc:
ImportLocalAlloc();
break;
case ILOpcode.endfilter:
ImportEndFilter();
return;
case ILOpcode.unaligned:
ImportUnalignedPrefix(ReadILByte());
continue;
case ILOpcode.volatile_:
ImportVolatilePrefix();
continue;
case ILOpcode.tail:
ImportTailPrefix();
continue;
case ILOpcode.initobj:
ImportInitObj(ReadILToken());
break;
case ILOpcode.constrained:
ImportConstrainedPrefix(ReadILToken());
continue;
case ILOpcode.cpblk:
ImportCpBlk();
break;
case ILOpcode.initblk:
ImportInitBlk();
break;
case ILOpcode.no:
ImportNoPrefix(ReadILByte());
continue;
case ILOpcode.rethrow:
ImportRethrow();
return;
case ILOpcode.sizeof_:
ImportSizeOf(ReadILToken());
break;
case ILOpcode.refanytype:
ImportRefAnyType();
break;
case ILOpcode.readonly_:
ImportReadOnlyPrefix();
continue;
default:
ReportInvalidInstruction(opCode);
EndImportingInstruction();
return;
}
EndImportingInstruction();
// Check if control falls through the end of method.
if (_currentOffset >= _basicBlocks.Length)
{
ReportFallthroughAtEndOfMethod();
return;
}
BasicBlock nextBasicBlock = _basicBlocks[_currentOffset];
if (nextBasicBlock != null)
{
ImportFallthrough(nextBasicBlock);
return;
}
}
}
private void ImportLoadIndirect(WellKnownType wellKnownType)
{
ImportLoadIndirect(GetWellKnownType(wellKnownType));
}
private void ImportStoreIndirect(WellKnownType wellKnownType)
{
ImportStoreIndirect(GetWellKnownType(wellKnownType));
}
private void ImportLoadElement(WellKnownType wellKnownType)
{
ImportLoadElement(GetWellKnownType(wellKnownType));
}
private void ImportStoreElement(WellKnownType wellKnownType)
{
ImportStoreElement(GetWellKnownType(wellKnownType));
}
}
}
| |
// ------------------------------------------------------------------------------
// 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.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type OpenTypeExtensionRequest.
/// </summary>
public partial class OpenTypeExtensionRequest : BaseRequest, IOpenTypeExtensionRequest
{
/// <summary>
/// Constructs a new OpenTypeExtensionRequest.
/// </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 OpenTypeExtensionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified OpenTypeExtension using POST.
/// </summary>
/// <param name="openTypeExtensionToCreate">The OpenTypeExtension to create.</param>
/// <returns>The created OpenTypeExtension.</returns>
public System.Threading.Tasks.Task<OpenTypeExtension> CreateAsync(OpenTypeExtension openTypeExtensionToCreate)
{
return this.CreateAsync(openTypeExtensionToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified OpenTypeExtension using POST.
/// </summary>
/// <param name="openTypeExtensionToCreate">The OpenTypeExtension to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created OpenTypeExtension.</returns>
public async System.Threading.Tasks.Task<OpenTypeExtension> CreateAsync(OpenTypeExtension openTypeExtensionToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<OpenTypeExtension>(openTypeExtensionToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified OpenTypeExtension.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified OpenTypeExtension.
/// </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<OpenTypeExtension>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified OpenTypeExtension.
/// </summary>
/// <returns>The OpenTypeExtension.</returns>
public System.Threading.Tasks.Task<OpenTypeExtension> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified OpenTypeExtension.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The OpenTypeExtension.</returns>
public async System.Threading.Tasks.Task<OpenTypeExtension> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<OpenTypeExtension>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified OpenTypeExtension using PATCH.
/// </summary>
/// <param name="openTypeExtensionToUpdate">The OpenTypeExtension to update.</param>
/// <returns>The updated OpenTypeExtension.</returns>
public System.Threading.Tasks.Task<OpenTypeExtension> UpdateAsync(OpenTypeExtension openTypeExtensionToUpdate)
{
return this.UpdateAsync(openTypeExtensionToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified OpenTypeExtension using PATCH.
/// </summary>
/// <param name="openTypeExtensionToUpdate">The OpenTypeExtension to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated OpenTypeExtension.</returns>
public async System.Threading.Tasks.Task<OpenTypeExtension> UpdateAsync(OpenTypeExtension openTypeExtensionToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<OpenTypeExtension>(openTypeExtensionToUpdate, 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 IOpenTypeExtensionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IOpenTypeExtensionRequest Expand(Expression<Func<OpenTypeExtension, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IOpenTypeExtensionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IOpenTypeExtensionRequest Select(Expression<Func<OpenTypeExtension, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="openTypeExtensionToInitialize">The <see cref="OpenTypeExtension"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(OpenTypeExtension openTypeExtensionToInitialize)
{
}
}
}
| |
//
// 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.IO;
using System.Text;
using Encog.Util.File;
using Encog.Util.Logging;
namespace Encog.Persist
{
/// <summary>
/// Handles Encog persistence for a directory. This is the usual mode where each
/// resource is stored in a separate EG file.
/// </summary>
///
public class EncogDirectoryPersistence
{
/// <summary>
/// The directory that holds the EG files.
/// </summary>
///
private readonly FileInfo _parent;
/// <summary>
/// Construct the object.
/// </summary>
///
/// <param name="parent">The directory to use.</param>
public EncogDirectoryPersistence(FileInfo parent)
{
_parent = parent;
}
/// <value>The directory.</value>
public FileInfo Parent
{
get { return _parent; }
}
/// <summary>
/// Load the specified object.
/// </summary>
///
/// <param name="file">The file to load.</param>
/// <returns>The loaded object.</returns>
public static Object LoadObject(FileInfo file)
{
FileStream fis = null;
try
{
fis = file.OpenRead();
Object result = LoadObject(fis);
return result;
}
catch (IOException ex)
{
throw new PersistError(ex);
}
finally
{
if (fis != null)
{
try
{
fis.Close();
}
catch (IOException e)
{
EncogLogging.Log(e);
}
}
}
}
/// <summary>
/// Load an EG object as a reousrce.
/// </summary>
/// <param name="res">The resource to load.</param>
/// <returns>The loaded object.</returns>
public static Object LoadResourceObject(String res)
{
using (Stream s = ResourceLoader.CreateStream(res))
{
return LoadObject(s);
}
}
/// <summary>
/// Load an object from an input stream.
/// </summary>
///
/// <param name="mask0">The input stream to read from.</param>
/// <returns>The loaded object.</returns>
public static Object LoadObject(Stream mask0)
{
String header = ReadLine(mask0);
String[] paras = header.Split(',');
if (!"encog".Equals(paras[0]))
{
throw new PersistError("Not a valid EG file.");
}
String name = paras[1];
IEncogPersistor p = PersistorRegistry.Instance.GetPersistor(
name);
if (p == null)
{
throw new PersistError("Do not know how to read the object: "
+ name);
}
if (p.FileVersion < Int32.Parse(paras[4]))
{
throw new PersistError(
"The file you are trying to read is from a later version of Encog. Please upgrade Encog to read this file.");
}
return p.Read(mask0);
}
/// <summary>
/// Read a line from the input stream.
/// </summary>
///
/// <param name="mask0">The input stream.</param>
/// <returns>The line read.</returns>
private static String ReadLine(Stream mask0)
{
try
{
var result = new StringBuilder();
char ch;
do
{
int b = mask0.ReadByte();
if (b == -1)
{
return result.ToString();
}
ch = (char) b;
if ((ch != 13) && (ch != 10))
{
result.Append(ch);
}
} while (ch != 10);
return result.ToString();
}
catch (IOException ex)
{
throw new PersistError(ex);
}
}
/// <summary>
/// Save the specified object.
/// </summary>
///
/// <param name="filename">The filename to save to.</param>
/// <param name="obj">The Object to save.</param>
public static void SaveObject(FileInfo filename, Object obj)
{
FileStream fos = null;
try
{
filename.Delete();
fos = filename.OpenWrite();
SaveObject(fos, obj);
}
catch (IOException ex)
{
throw new PersistError(ex);
}
finally
{
try
{
if (fos != null)
{
fos.Close();
}
}
catch (IOException e)
{
EncogLogging.Log(e);
}
}
}
/// <summary>
/// Save the specified object.
/// </summary>
///
/// <param name="os">The output stream to write to.</param>
/// <param name="obj">The object to save.</param>
public static void SaveObject(Stream os, Object obj)
{
try
{
IEncogPersistor p = PersistorRegistry.Instance
.GetPersistor(obj.GetType());
if (p == null)
{
throw new PersistError("Do not know how to persist object: "
+ obj.GetType().Name);
}
os.Flush();
var pw = new StreamWriter(os);
DateTime now = DateTime.Now;
pw.WriteLine("encog," + p.PersistClassString + ",java,"
+ EncogFramework.Version + "," + p.FileVersion + ","
+ (now.Ticks/10000));
pw.Flush();
p.Save(os, obj);
}
catch (IOException ex)
{
throw new PersistError(ex);
}
}
/// <summary>
/// Get the type of an Encog object in an EG file, without the
/// need to read the entire file.
/// </summary>
///
/// <param name="name">The filename to read.</param>
/// <returns>The type.</returns>
public String GetEncogType(String name)
{
try
{
var path = new FileInfo(Path.Combine(_parent.FullName, name));
TextReader br = new StreamReader(path.OpenRead());
String header = br.ReadLine();
String[] paras = header.Split(',');
br.Close();
return paras[1];
}
catch (IOException ex)
{
throw new PersistError(ex);
}
}
/// <summary>
/// Load a file from the directory that this object refers to.
/// </summary>
///
/// <param name="name">The name to load.</param>
/// <returns>The object.</returns>
public Object LoadFromDirectory(String name)
{
var path = new FileInfo(Path.Combine(_parent.FullName, name));
return LoadObject(path);
}
/// <summary>
/// Save a file to the directory that this object refers to.
/// </summary>
///
/// <param name="name">The name to load.</param>
/// <param name="obj">The object.</param>
public void SaveToDirectory(String name, Object obj)
{
var path = new FileInfo(Path.Combine(_parent.FullName, name));
SaveObject(path, obj);
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Remoting.Channels;
using System.Threading;
using Belikov.GenuineChannels;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
namespace Belikov.GenuineChannels.Security.SSPI
{
/// <summary>
/// Implements client-side SSPI Security Session that
/// establishes SSPI security context and can encrypt and/or sign content.
/// </summary>
public class SecuritySession_SspiClient : SecuritySession
{
/// <summary>
/// Constructs an instance of the SecuritySession_SspiClient class.
/// </summary>
/// <param name="name">The name of the Security Session.</param>
/// <param name="remote">The remote host.</param>
/// <param name="keyProvider_SspiClient">Parent KeyProvider_SspiClient instance to get settings from.</param>
public SecuritySession_SspiClient(string name, HostInformation remote, KeyProvider_SspiClient keyProvider_SspiClient)
: base(name, remote)
{
this.KeyProvider_SspiClient = keyProvider_SspiClient;
}
/// <summary>
/// Parent KeyProvider_SspiClient instance to get settings from.
/// </summary>
public KeyProvider_SspiClient KeyProvider_SspiClient;
/// <summary>
/// SSPI security context.
/// </summary>
public SspiClientSecurityContext SspiSecurityContext;
/// <summary>
/// Initialization process will be restarted if authentication was not finished within this
/// time span.
/// </summary>
public static TimeSpan MaxSpanToPerformAuthentication = TimeSpan.FromMinutes(3);
#region -- Establish security context ------------------------------------------------------
/// <summary>
/// Initiates or continues establishing of the Security Session.
/// Implementation notes: receiving of exceptions no more breaks up the connection like
/// it was in the previous versions.
/// </summary>
/// <param name="input">A null reference or an incoming stream.</param>
/// <param name="connectionLevel">Indicates whether the Security Session operates on connection level.</param>
/// <returns>A stream containing data for sending to the remote host or a null reference if Security Session is established.</returns>
public override GenuineChunkedStream EstablishSession(Stream input, bool connectionLevel)
{
bool passException = false;
// a dance is over
if (this.IsEstablished)
return null;
GenuineChunkedStream outputStream = null;
BinaryFormatter binaryFormatter = new BinaryFormatter();
// skip the status flag
if (connectionLevel)
{
if (input != null)
input.ReadByte();
outputStream = new GenuineChunkedStream(false);
}
else
outputStream = this.CreateOutputStream();
// write session is being established flag
BinaryWriter binaryWriter = new BinaryWriter(outputStream);
binaryWriter.Write((byte) 0);
try
{
lock(this)
{
if (input == Stream.Null)
{
if (this.KeyProvider_SspiClient.DelegatedContext != null)
{
try
{
SspiApi.ImpersonateSecurityContext(this.KeyProvider_SspiClient.DelegatedContext.SspiSecurityContext._phContext);
// start new session
this.SspiSecurityContext = new SspiClientSecurityContext(this.KeyProvider_SspiClient);
binaryWriter.Write((byte) SspiPacketStatusFlags.InitializeFromScratch);
this.SspiSecurityContext.BuildUpSecurityContext(null, outputStream);
return outputStream;
}
finally
{
SspiApi.RevertSecurityContext(this.KeyProvider_SspiClient.DelegatedContext.SspiSecurityContext._phContext);
}
}
// start new session
this.SspiSecurityContext = new SspiClientSecurityContext(this.KeyProvider_SspiClient);
binaryWriter.Write((byte) SspiPacketStatusFlags.InitializeFromScratch);
this.SspiSecurityContext.BuildUpSecurityContext(null, outputStream);
return outputStream;
}
SspiPacketStatusFlags sspiPacketStatusFlags = (SspiPacketStatusFlags) input.ReadByte();
switch (sspiPacketStatusFlags)
{
case SspiPacketStatusFlags.ContinueAuthentication:
// continue building a security context
GenuineChunkedStream sspiData = new GenuineChunkedStream(false);
this.SspiSecurityContext.BuildUpSecurityContext(input, sspiData);
if (sspiData.Length == 0)
{
// SSPI session has been built up
outputStream.WriteByte((byte) SspiPacketStatusFlags.SessionEstablished);
this.SessionEstablished();
}
else
{
outputStream.WriteByte((byte) SspiPacketStatusFlags.ContinueAuthentication);
outputStream.WriteStream(sspiData);
}
return outputStream;
case SspiPacketStatusFlags.ExceptionThrown:
Exception receivedException = GenuineUtility.ReadException(input);
#if DEBUG
// this.Remote.ITransportContext.IEventLogger.Log(LogMessageCategory.Security, receivedException, "SecuritySession_SspiServer.EstablishSession",
// null, "SSPI initialization ends up with an exception at the remote host. Remote host: {0}.",
// this.Remote.ToString());
#endif
if (this.Remote != null)
this.Remote.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(
GenuineEventType.SecuritySessionFailed, receivedException, this.Remote, this));
this.DispatchException(receivedException);
passException = true;
throw receivedException;
case SspiPacketStatusFlags.ForceInitialization:
return this.EstablishSession(Stream.Null, connectionLevel);
case SspiPacketStatusFlags.InitializeFromScratch:
throw GenuineExceptions.Get_Processing_LogicError(
string.Format("The remote host must have the Security Session of the type SecuritySession_SspiServer registered with the name {0}. SecuritySession_SspiServer never sends SspiPacketMark.InitializeFromScratch packet marker.",
this.Name));
case SspiPacketStatusFlags.SessionEstablished:
this.SessionEstablished();
break;
}
}
}
catch(Exception opEx)
{
#if DEBUG
// this.Remote.ITransportContext.IEventLogger.Log(LogMessageCategory.Security, opEx, "SecuritySession_SspiServer.EstablishSession",
// null, "Exception was thrown while establishing security context.");
#endif
if (this.Remote != null)
this.Remote.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(
GenuineEventType.SecuritySessionFailed, opEx, this.Remote, this));
this.DispatchException(opEx);
if (passException)
throw;
binaryWriter.Write((byte) SspiPacketStatusFlags.ExceptionThrown);
binaryFormatter.Serialize(outputStream, opEx);
return outputStream;
}
return null;
}
#endregion
#region -- Cryptography --------------------------------------------------------------------
/// <summary>
/// Encrypts the message data and put a result into the specified output stream.
/// </summary>
/// <param name="input">The stream containing the serialized message.</param>
/// <param name="output">The result stream with the data being sent to the remote host.</param>
public override void Encrypt(Stream input, GenuineChunkedStream output)
{
// write session established flag
output.WriteByte(1);
// serialize messages into separate stream
this.SspiSecurityContext.EncryptMessage(input, output, this.KeyProvider_SspiClient.RequiredFeatures);
}
/// <summary>
/// Creates and returns a stream containing decrypted data.
/// </summary>
/// <param name="input">A stream containing encrypted data.</param>
/// <returns>A stream with decrypted data.</returns>
public override Stream Decrypt(Stream input)
{
if (input.ReadByte() == 0)
{
Stream outputStream = this.EstablishSession(input, false);
if (outputStream != null)
GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.SendMessage), outputStream, false);
return null;
}
return this.SspiSecurityContext.DecryptMessage(input, this.KeyProvider_SspiClient.RequiredFeatures);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Cryptography.Pal;
using System.Diagnostics;
using System.Globalization;
namespace System.Security.Cryptography.X509Certificates
{
public sealed class X509Store : IDisposable
{
internal const string RootStoreName = "Root";
internal const string IntermediateCAStoreName = "CA";
internal const string DisallowedStoreName = "Disallowed";
internal const string MyStoreName = "My";
private IStorePal _storePal;
public X509Store()
: this("MY", StoreLocation.CurrentUser)
{
}
public X509Store(string storeName)
: this(storeName, StoreLocation.CurrentUser)
{
}
public X509Store(StoreName storeName)
: this(storeName, StoreLocation.CurrentUser)
{
}
public X509Store(StoreLocation storeLocation)
: this("MY", storeLocation)
{
}
public X509Store(StoreName storeName, StoreLocation storeLocation)
{
if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeLocation)));
Name = storeName switch
{
StoreName.AddressBook => "AddressBook",
StoreName.AuthRoot => "AuthRoot",
StoreName.CertificateAuthority => IntermediateCAStoreName,
StoreName.Disallowed => DisallowedStoreName,
StoreName.My => MyStoreName,
StoreName.Root => RootStoreName,
StoreName.TrustedPeople => "TrustedPeople",
StoreName.TrustedPublisher => "TrustedPublisher",
_ => throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeName))),
};
Location = storeLocation;
}
public X509Store(StoreName storeName, StoreLocation storeLocation, OpenFlags flags)
: this(storeName, storeLocation)
{
Open(flags);
}
public X509Store(string storeName, StoreLocation storeLocation)
{
if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeLocation)));
Location = storeLocation;
Name = storeName;
}
public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags)
: this(storeName, storeLocation)
{
Open(flags);
}
public X509Store(IntPtr storeHandle)
{
_storePal = StorePal.FromHandle(storeHandle);
Debug.Assert(_storePal != null);
}
public IntPtr StoreHandle
{
get
{
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
// The Pal layer may return null (Unix) or throw exception (Windows)
if (_storePal.SafeHandle == null)
return IntPtr.Zero;
return _storePal.SafeHandle.DangerousGetHandle();
}
}
public StoreLocation Location { get; private set; }
public string Name { get; private set; }
public void Open(OpenFlags flags)
{
Close();
_storePal = StorePal.FromSystemStore(Name, Location, flags);
}
public X509Certificate2Collection Certificates
{
get
{
X509Certificate2Collection certificates = new X509Certificate2Collection();
if (_storePal != null)
{
_storePal.CloneTo(certificates);
}
return certificates;
}
}
public bool IsOpen
{
get { return _storePal != null; }
}
public void Add(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
if (certificate.Pal == null)
throw new CryptographicException(SR.Cryptography_InvalidHandle, "pCertContext");
_storePal.Add(certificate.Pal);
}
public void AddRange(X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException(nameof(certificates));
int i = 0;
try
{
foreach (X509Certificate2 certificate in certificates)
{
Add(certificate);
i++;
}
}
catch
{
// For desktop compat, we keep the exception semantics even though they are not ideal
// because an exception may cause certs to be removed even if they weren't there before.
for (int j = 0; j < i; j++)
{
Remove(certificates[j]);
}
throw;
}
}
public void Remove(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
if (certificate.Pal == null)
return;
_storePal.Remove(certificate.Pal);
}
public void RemoveRange(X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException(nameof(certificates));
int i = 0;
try
{
foreach (X509Certificate2 certificate in certificates)
{
Remove(certificate);
i++;
}
}
catch
{
// For desktop compat, we keep the exception semantics even though they are not ideal
// because an exception above may cause certs to be added even if they weren't there before
// and an exception here may cause certs not to be re-added.
for (int j = 0; j < i; j++)
{
Add(certificates[j]);
}
throw;
}
}
public void Dispose()
{
Close();
}
public void Close()
{
IStorePal storePal = _storePal;
_storePal = null;
if (storePal != null)
{
storePal.Dispose();
}
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using System.Collections.Immutable;
using Xunit;
using Roslyn.Test.PdbUtilities;
using Microsoft.VisualStudio.Debugger.Evaluation;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class NoPIATests : ExpressionCompilerTestBase
{
[WorkItem(1033598)]
[Fact]
public void ExplicitEmbeddedType()
{
var source =
@"using System.Runtime.InteropServices;
[TypeIdentifier]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9D8"")]
public interface I
{
object F();
}
class C
{
void M()
{
var o = (I)null;
}
static void Main()
{
(new C()).M();
}
}";
var compilation0 = CSharpTestBase.CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugExe,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
var runtime = CreateRuntimeInstance(compilation0);
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("this", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (I V_0) //o
IL_0000: ldarg.0
IL_0001: ret
}");
}
[WorkItem(1035310)]
[Fact]
public void EmbeddedType()
{
var sourcePIA =
@"using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssembly(0, 0)]
[assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DA"")]
[ComImport]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DA"")]
public interface I
{
object F();
}";
var source =
@"class C
{
static void M()
{
var o = (I)null;
}
}";
var compilationPIA = CreateCompilationWithMscorlib(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: Guid.NewGuid().ToString("D"),
references: new MetadataReference[] { referencePIA });
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
// References should not include PIA.
Assert.Equal(references.Length, 1);
Assert.True(references[0].Display.StartsWith("mscorlib", StringComparison.Ordinal));
var runtime = CreateRuntimeInstance(
Guid.NewGuid().ToString("D"),
references,
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("o", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (I V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}");
}
/// <summary>
/// Duplicate type definitions: in PIA
/// and as embedded type.
/// </summary>
[Fact]
public void PIATypeAndEmbeddedType()
{
var sourcePIA =
@"using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssembly(0, 0)]
[assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DC"")]
[ComImport]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DC"")]
public interface I
{
object F();
}";
var sourceA =
@"public class A
{
public static void M(I x)
{
}
}";
var sourceB =
@"class B
{
static void Main()
{
I y = null;
A.M(y);
}
}";
var compilationPIA = CreateCompilationWithMscorlib(sourcePIA, options: TestOptions.DebugDll);
byte[] exePIA;
byte[] pdbPIA;
ImmutableArray<MetadataReference> referencesPIA;
compilationPIA.EmitAndGetReferences(out exePIA, out pdbPIA, out referencesPIA);
var metadataPIA = AssemblyMetadata.CreateFromImage(exePIA);
var referencePIA = metadataPIA.GetReference();
// csc /t:library /l:PIA.dll A.cs
var compilationA = CreateCompilationWithMscorlib(
sourceA,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: new MetadataReference[] { metadataPIA.GetReference(embedInteropTypes: true) });
byte[] exeA;
byte[] pdbA;
ImmutableArray<MetadataReference> referencesA;
compilationA.EmitAndGetReferences(out exeA, out pdbA, out referencesA);
var metadataA = AssemblyMetadata.CreateFromImage(exeA);
var referenceA = metadataA.GetReference();
// csc /r:A.dll /r:PIA.dll B.cs
var compilationB = CreateCompilationWithMscorlib(
sourceB,
options: TestOptions.DebugExe,
assemblyName: Guid.NewGuid().ToString("D"),
references: new MetadataReference[] { metadataA.GetReference(), metadataPIA.GetReference() });
byte[] exeB;
byte[] pdbB;
ImmutableArray<MetadataReference> referencesB;
compilationB.EmitAndGetReferences(out exeB, out pdbB, out referencesB);
var metadataB = AssemblyMetadata.CreateFromImage(exeB);
var referenceB = metadataB.GetReference();
// Create runtime from modules { mscorlib, PIA, A, B }.
var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance();
modulesBuilder.Add(MscorlibRef.ToModuleInstance(fullImage: null, symReader: null));
modulesBuilder.Add(referenceA.ToModuleInstance(fullImage: exeA, symReader: new SymReader(pdbA)));
modulesBuilder.Add(referencePIA.ToModuleInstance(fullImage: null, symReader: null));
modulesBuilder.Add(referenceB.ToModuleInstance(fullImage: exeB, symReader: new SymReader(pdbB)));
using (var runtime = new RuntimeInstance(modulesBuilder.ToImmutableAndFree()))
{
var context = CreateMethodContext(runtime, "A.M");
ResultProperties resultProperties;
string error;
// Bind to local of embedded PIA type.
var testData = new CompilationTestData();
context.CompileExpression("x", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
// Binding to method on original PIA should fail
// since it was not included in embedded type.
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileExpression(
"x.F()",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity);
Assert.Equal(error, "error CS1061: 'I' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?)");
// Binding to method on original PIA should succeed
// in assembly referencing PIA.dll.
context = CreateMethodContext(runtime, "B.Main");
testData = new CompilationTestData();
context.CompileExpression("y.F()", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
.locals init (I V_0) //y
IL_0000: ldloc.0
IL_0001: callvirt ""object I.F()""
IL_0006: ret
}");
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// DistinctQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// This operator yields all of the distinct elements in a single data set. It works quite
/// like the above set operations, with the obvious difference being that it only accepts
/// a single data source as input.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
internal sealed class DistinctQueryOperator<TInputOutput> : UnaryQueryOperator<TInputOutput, TInputOutput>
{
private readonly IEqualityComparer<TInputOutput> _comparer; // An (optional) equality comparer.
//---------------------------------------------------------------------------------------
// Constructs a new distinction operator.
//
internal DistinctQueryOperator(IEnumerable<TInputOutput> source, IEqualityComparer<TInputOutput> comparer)
: base(source)
{
Debug.Assert(source != null, "child data source cannot be null");
_comparer = comparer;
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TInputOutput> Open(QuerySettings settings, bool preferStriping)
{
// We just open our child operator. Do not propagate the preferStriping value, but
// instead explicitly set it to false. Regardless of whether the parent prefers striping or range
// partitioning, the output will be hash-partitioned.
QueryResults<TInputOutput> childResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childResults, this, settings, false);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings)
{
// Hash-repartition the source stream
if (OutputOrdered)
{
WrapPartitionedStreamHelper<TKey>(
ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TKey>(
inputStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken),
recipient, settings.CancellationState.MergedCancellationToken);
}
else
{
WrapPartitionedStreamHelper<int>(
ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TKey>(
inputStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken),
recipient, settings.CancellationState.MergedCancellationToken);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TKey>(
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> hashStream,
IPartitionedStreamRecipient<TInputOutput> recipient, CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<TInputOutput, TKey> outputStream =
new PartitionedStream<TInputOutput, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
if (OutputOrdered)
{
outputStream[i] =
new OrderedDistinctQueryOperatorEnumerator<TKey>(hashStream[i], _comparer, hashStream.KeyComparer, cancellationToken);
}
else
{
outputStream[i] = (QueryOperatorEnumerator<TInputOutput, TKey>)(object)
new DistinctQueryOperatorEnumerator<TKey>(hashStream[i], _comparer, cancellationToken);
}
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// 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; }
}
//---------------------------------------------------------------------------------------
// This enumerator performs the distinct operation incrementally. It does this by
// maintaining a history -- in the form of a set -- of all data already seen. It simply
// then doesn't return elements it has already seen before.
//
class DistinctQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TInputOutput, int>
{
private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> _source; // The data source.
private Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the distinct set.
private CancellationToken _cancellationToken;
private Shared<int> _outputLoopCount; // Allocated in MoveNext to avoid false sharing.
//---------------------------------------------------------------------------------------
// Instantiates a new distinction operator.
//
internal DistinctQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> source, IEqualityComparer<TInputOutput> comparer,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_hashLookup = new Set<TInputOutput>(comparer);
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the single data source, skipping elements it has already seen.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey)
{
Debug.Assert(_source != null);
Debug.Assert(_hashLookup != null);
// Iterate over this set's elements until we find a unique element.
TKey keyUnused = default(TKey);
Pair<TInputOutput, NoKeyMemoizationRequired> current = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
if (_outputLoopCount == null)
_outputLoopCount = new Shared<int>(0);
while (_source.MoveNext(ref current, ref keyUnused))
{
if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We ensure we never return duplicates by tracking them in our set.
if (_hashLookup.Add(current.First))
{
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
currentElement = current.First;
return true;
}
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
return wrappedChild.Distinct(_comparer);
}
class OrderedDistinctQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TInputOutput, TKey>
{
private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> _source; // The data source.
private Dictionary<Wrapper<TInputOutput>, TKey> _hashLookup; // The hash lookup, used to produce the distinct set.
private IComparer<TKey> _keyComparer; // Comparer to decide the key order.
private IEnumerator<KeyValuePair<Wrapper<TInputOutput>, TKey>> _hashLookupEnumerator; // Enumerates over _hashLookup.
private CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new distinction operator.
//
internal OrderedDistinctQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TKey> source,
IEqualityComparer<TInputOutput> comparer, IComparer<TKey> keyComparer,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_keyComparer = keyComparer;
_hashLookup = new Dictionary<Wrapper<TInputOutput>, TKey>(
new WrapperEqualityComparer<TInputOutput>(comparer));
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the single data source, skipping elements it has already seen.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref TKey currentKey)
{
Debug.Assert(_source != null);
Debug.Assert(_hashLookup != null);
if (_hashLookupEnumerator == null)
{
Pair<TInputOutput, NoKeyMemoizationRequired> elem = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
TKey orderKey = default(TKey);
int i = 0;
while (_source.MoveNext(ref elem, ref orderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// For each element, we track the smallest order key for that element that we saw so far
TKey oldEntry;
Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>(elem.First);
// If this is the first occurrence of this element, or the order key is lower than all keys we saw previously,
// update the order key for this element.
if (!_hashLookup.TryGetValue(wrappedElem, out oldEntry) || _keyComparer.Compare(orderKey, oldEntry) < 0)
{
// For each "elem" value, we store the smallest key, and the element value that had that key.
// Note that even though two element values are "equal" according to the EqualityComparer,
// we still cannot choose arbitrarily which of the two to yield.
_hashLookup[wrappedElem] = orderKey;
}
}
_hashLookupEnumerator = _hashLookup.GetEnumerator();
}
if (_hashLookupEnumerator.MoveNext())
{
KeyValuePair<Wrapper<TInputOutput>, TKey> currentPair = _hashLookupEnumerator.Current;
currentElement = currentPair.Key.Value;
currentKey = currentPair.Value;
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
if (_hashLookupEnumerator != null)
{
_hashLookupEnumerator.Dispose();
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Baseline;
using Marten.Events;
using Marten.Events.Aggregation;
using Marten.Events.CodeGeneration;
using Marten.Events.Projections;
using Marten.Exceptions;
using Marten.Storage;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
namespace Marten.Testing.Events.Aggregation
{
public class aggregation_projection_validation_rules
{
protected string errorMessageFor(Action<StoreOptions> configure)
{
var ex = Should.Throw<InvalidProjectionException>(() =>
{
DocumentStore.For(opts =>
{
opts.Connection(ConnectionSource.ConnectionString);
configure(opts);
});
});
return ex.Message;
}
[Fact]
public void aggregate_id_is_wrong_type_1()
{
var message = errorMessageFor(x =>
{
x.Events.StreamIdentity = StreamIdentity.AsGuid;
x.Projections.SelfAggregate<StringIdentifiedAggregate>(ProjectionLifecycle.Async);
});
message.ShouldContain("Id type mismatch. The stream identity type is System.Guid, but the aggregate document Marten.Testing.Events.Aggregation.aggregation_projection_validation_rules.StringIdentifiedAggregate id type is string", StringComparisonOption.Default);
}
[Fact]
public void aggregate_id_is_wrong_type_2()
{
var message = errorMessageFor(x =>
{
x.Events.StreamIdentity = StreamIdentity.AsString;
x.Projections.SelfAggregate<GuidIdentifiedAggregate>(ProjectionLifecycle.Async);
});
message.ShouldContain("Id type mismatch. The stream identity type is string, but the aggregate document Marten.Testing.Events.Aggregation.aggregation_projection_validation_rules.GuidIdentifiedAggregate id type is Guid", StringComparisonOption.Default);
}
[Fact]
public void if_events_are_multi_tenanted_so_must_the_projected_view()
{
errorMessageFor(opts =>
{
opts.Events.TenancyStyle = TenancyStyle.Conjoined;
opts.Projections.SelfAggregate<GuidIdentifiedAggregate>(ProjectionLifecycle.Async);
}).ShouldContain("Tenancy storage style mismatch between the events (Conjoined) and the aggregate type Marten.Testing.Events.Aggregation.aggregation_projection_validation_rules.GuidIdentifiedAggregate (Single)", StringComparisonOption.Default);
}
[Fact]
public void if_the_aggregate_is_multi_tenanted_but_the_events_are_not()
{
errorMessageFor(opts =>
{
opts.Projections.SelfAggregate<GuidIdentifiedAggregate>(ProjectionLifecycle.Async);
opts.Schema.For<GuidIdentifiedAggregate>().MultiTenanted();
}).ShouldContain("Tenancy storage style mismatch between the events (Single) and the aggregate type Marten.Testing.Events.Aggregation.aggregation_projection_validation_rules.GuidIdentifiedAggregate (Conjoined)", StringComparisonOption.Default);
}
[Fact]
public void validation_errors_on_empty_aggregation()
{
errorMessageFor(opts =>
{
opts.Projections.Add(new Projections.EmptyProjection());
}).ShouldNotBeNull();
}
public class EmptyProjection: AggregateProjection<GuidIdentifiedAggregate>
{
}
public class GuidIdentifiedAggregate
{
public Guid Id { get; set; }
public void Apply(AEvent a)
{
}
}
public class StringIdentifiedAggregate
{
public string Id { get; set; }
public void Apply(AEvent a)
{
}
}
[Fact]
public void happy_path_validation_for_aggregation()
{
var projection = new AllGood();
projection.AssertValidity();
}
[Fact]
public void find_bad_method_names_that_are_not_ignored()
{
var projection = new BadMethodName();
var ex = Should.Throw<InvalidProjectionException>(() => projection.AssertValidity());
ex.Message.ShouldContain("Unrecognized method name 'DoStuff'. Either mark with [MartenIgnore] or use one of 'Apply', 'Create', 'ShouldDelete'", StringComparisonOption.NormalizeWhitespaces);
}
[Fact]
public void find_invalid_argument_type()
{
var projection = new InvalidArgumentType();
var ex = Should.Throw<InvalidProjectionException>(() => projection.AssertValidity());
ex.InvalidMethods.Single()
.Errors
.ShouldContain("Parameter of type 'Marten.IDocumentOperations' is not supported. Valid options are System.Threading.CancellationToken, Marten.IQuerySession, Marten.Testing.Events.Aggregation.MyAggregate, Marten.Testing.Events.Aggregation.AEvent, Marten.Events.IEvent, Marten.Events.IEvent<Marten.Testing.Events.Aggregation.AEvent>");
}
[Fact]
public void missing_event_altogether()
{
var projection = new MissingEventType1();
var ex = Should.Throw<InvalidProjectionException>(() => projection.AssertValidity());
ex.InvalidMethods.Single()
.Errors.ShouldContain(MethodSlot.NoEventType);
}
[Fact]
public void marten_can_guess_the_event_based_on_what_is_left()
{
var projection = new CanGuessEventType();
projection.AssertValidity();
}
[Fact]
public void invalid_return_type()
{
var projection = new BadReturnType();
var ex = Should.Throw<InvalidProjectionException>(() => projection.AssertValidity());
ex.InvalidMethods.Single()
.Errors.ShouldContain(
"Parameter of type 'Marten.IDocumentOperations' is not supported. Valid options are System.Threading.CancellationToken, Marten.IQuerySession, Marten.Testing.Events.Aggregation.MyAggregate, Marten.Testing.Events.Aggregation.AEvent, Marten.Events.IEvent, Marten.Events.IEvent<Marten.Testing.Events.Aggregation.AEvent>", "Return type 'string' is invalid. The valid options are System.Threading.CancellationToken, Marten.IQuerySession, Marten.Testing.Events.Aggregation.MyAggregate");
}
[Fact]
public void missing_required_parameter()
{
var projection = new MissingMandatoryType();
var ex = Should.Throw<InvalidProjectionException>(() => projection.AssertValidity());
ex.InvalidMethods.Single()
.Errors.ShouldContain("Aggregate type 'Marten.Testing.Events.Aggregation.MyAggregate' is required as a parameter");
}
}
public class MissingMandatoryType: AggregateProjection<MyAggregate>
{
public void Apply(AEvent @event)
{
}
}
public class BadReturnType: AggregateProjection<MyAggregate>
{
public string Apply(AEvent @event, MyAggregate aggregate, IDocumentOperations operations)
{
return null;
}
}
public class MissingEventType1: AggregateProjection<MyAggregate>
{
public void Apply(MyAggregate aggregate, IDocumentOperations operations)
{
}
}
public class CanGuessEventType: AggregateProjection<MyAggregate>
{
public void Apply(AEvent a, MyAggregate aggregate, IQuerySession session)
{
}
}
public class InvalidArgumentType: AggregateProjection<MyAggregate>
{
public void Apply(AEvent @event, MyAggregate aggregate, IDocumentOperations operations)
{
}
}
public class BadMethodName: AggregateProjection<MyAggregate>
{
public void DoStuff(AEvent @event, MyAggregate aggregate)
{
}
public MyAggregate Create(CreateEvent @event)
{
return new MyAggregate
{
ACount = @event.A,
BCount = @event.B,
CCount = @event.C,
DCount = @event.D
};
}
}
public class AllGood: AggregateProjection<MyAggregate>
{
public AllGood()
{
ProjectionName = "AllGood";
}
[MartenIgnore]
public void RandomMethodName()
{
}
public MyAggregate Create(CreateEvent @event)
{
return new MyAggregate
{
ACount = @event.A,
BCount = @event.B,
CCount = @event.C,
DCount = @event.D
};
}
public Task<MyAggregate> Create(CreateEvent @event, IQuerySession session)
{
return null;
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
public MyAggregate Apply(BEvent @event, MyAggregate aggregate)
{
return new MyAggregate
{
ACount = aggregate.ACount,
BCount = aggregate.BCount + 1,
CCount = aggregate.CCount,
DCount = aggregate.DCount,
Id = aggregate.Id
};
}
public void Apply(MyAggregate aggregate, CEvent @event)
{
aggregate.CCount++;
}
public MyAggregate Apply(MyAggregate aggregate, DEvent @event)
{
return new MyAggregate
{
ACount = aggregate.ACount,
BCount = aggregate.BCount,
CCount = aggregate.CCount,
DCount = aggregate.DCount + 1,
Id = aggregate.Id
};
}
}
}
| |
// 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.
//
// 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.Batch.Protocol
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobOperations operations.
/// </summary>
public partial interface IJobOperations
{
/// <summary>
/// Gets lifetime summary statistics for all of the jobs in the
/// specified account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all jobs that have ever existed
/// in the account, from account creation to the last update time of
/// the statistics.
/// </remarks>
/// <param name='jobGetAllJobsLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
Task<AzureOperationResponse<JobStatistics,JobGetAllJobsLifetimeStatisticsHeaders>> GetAllJobsLifetimeStatisticsWithHttpMessagesAsync(JobGetAllJobsLifetimeStatisticsOptions jobGetAllJobsLifetimeStatisticsOptions = default(JobGetAllJobsLifetimeStatisticsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a job.
/// </summary>
/// <param name='jobId'>
/// The id of the job to delete.
/// </param>
/// <param name='jobDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobDeleteHeaders>> DeleteWithHttpMessagesAsync(string jobId, JobDeleteOptions jobDeleteOptions = default(JobDeleteOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified job.
/// </summary>
/// <param name='jobId'>
/// The id of the job.
/// </param>
/// <param name='jobGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
Task<AzureOperationResponse<CloudJob,JobGetHeaders>> GetWithHttpMessagesAsync(string jobId, JobGetOptions jobGetOptions = default(JobGetOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the properties of a job.
/// </summary>
/// <param name='jobId'>
/// The id of the job whose properties you want to update.
/// </param>
/// <param name='jobPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobPatchHeaders>> PatchWithHttpMessagesAsync(string jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions = default(JobPatchOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the properties of a job.
/// </summary>
/// <param name='jobId'>
/// The id of the job whose properties you want to update.
/// </param>
/// <param name='jobUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobUpdateHeaders>> UpdateWithHttpMessagesAsync(string jobId, JobUpdateParameter jobUpdateParameter, JobUpdateOptions jobUpdateOptions = default(JobUpdateOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disables the specified job, preventing new tasks from running.
/// </summary>
/// <param name='jobId'>
/// The id of the job to disable.
/// </param>
/// <param name='disableTasks'>
/// What to do with active tasks associated with the job. Possible
/// values include: 'requeue', 'terminate', 'wait'
/// </param>
/// <param name='jobDisableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobDisableHeaders>> DisableWithHttpMessagesAsync(string jobId, DisableJobOption disableTasks, JobDisableOptions jobDisableOptions = default(JobDisableOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Enables the specified job, allowing new tasks to run.
/// </summary>
/// <param name='jobId'>
/// The id of the job to enable.
/// </param>
/// <param name='jobEnableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobEnableHeaders>> EnableWithHttpMessagesAsync(string jobId, JobEnableOptions jobEnableOptions = default(JobEnableOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Terminates the specified job, marking it as completed.
/// </summary>
/// <param name='jobId'>
/// The id of the job to terminate.
/// </param>
/// <param name='terminateReason'>
/// The text you want to appear as the job's TerminateReason. The
/// default is 'UserTerminate'.
/// </param>
/// <param name='jobTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobTerminateHeaders>> TerminateWithHttpMessagesAsync(string jobId, string terminateReason = default(string), JobTerminateOptions jobTerminateOptions = default(JobTerminateOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Adds a job to the specified account.
/// </summary>
/// <param name='job'>
/// The job to be added.
/// </param>
/// <param name='jobAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobAddHeaders>> AddWithHttpMessagesAsync(JobAddParameter job, JobAddOptions jobAddOptions = default(JobAddOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='jobListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
Task<AzureOperationResponse<IPage<CloudJob>,JobListHeaders>> ListWithHttpMessagesAsync(JobListOptions jobListOptions = default(JobListOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the jobs that have been created under the specified job
/// schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The id of the job schedule from which you want to get a list of
/// jobs.
/// </param>
/// <param name='jobListFromJobScheduleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
Task<AzureOperationResponse<IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleWithHttpMessagesAsync(string jobScheduleId, JobListFromJobScheduleOptions jobListFromJobScheduleOptions = default(JobListFromJobScheduleOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release
/// task for the specified job across the compute nodes where the job
/// has run.
/// </summary>
/// <param name='jobId'>
/// The id of the job.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
Task<AzureOperationResponse<IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusWithHttpMessagesAsync(string jobId, JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions = default(JobListPreparationAndReleaseTaskStatusOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
Task<AzureOperationResponse<IPage<CloudJob>,JobListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, JobListNextOptions jobListNextOptions = default(JobListNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the jobs that have been created under the specified job
/// schedule.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListFromJobScheduleNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
Task<AzureOperationResponse<IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleNextWithHttpMessagesAsync(string nextPageLink, JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions = default(JobListFromJobScheduleNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release
/// task for the specified job across the compute nodes where the job
/// has run.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
Task<AzureOperationResponse<IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusNextWithHttpMessagesAsync(string nextPageLink, JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = default(JobListPreparationAndReleaseTaskStatusNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// <copyright file="IPersistedQueue{T}.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IX.System.Collections.Generic;
using JetBrains.Annotations;
namespace IX.Guaranteed.Collections;
/// <summary>
/// A contract for a persisted queue.
/// </summary>
/// <typeparam name="T">The type of items in the queue.</typeparam>
[PublicAPI]
[global::System.Diagnostics.CodeAnalysis.SuppressMessage(
"Design",
"CA1010:Generic interface should also be implemented",
Justification = "This is not necessary.")]
public interface IPersistedQueue<T> : IQueue<T>
{
#region Methods
/// <summary>
/// Tries to load the topmost item and execute an action on it, deleting the topmost object data if the operation is
/// successful.
/// </summary>
/// <typeparam name="TState">The type of the state object to send to the action.</typeparam>
/// <param name="predicate">The predicate.</param>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the invoked action.</param>
/// <returns>The number of items that have been dequeued.</returns>
/// <remarks>
/// <para>
/// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the
/// <paramref name="predicate" /> method
/// filters out items in a way that limits the amount of data passing through.
/// </para>
/// </remarks>
int DequeueWhilePredicateWithAction<TState>(
Func<TState, T, bool> predicate,
Action<TState, IEnumerable<T>> actionToInvoke,
TState state);
/// <summary>
/// Tries asynchronously to load the topmost item and execute an action on it, deleting the topmost object data if the
/// operation is successful.
/// </summary>
/// <typeparam name="TState">The type of the state object to send to the action.</typeparam>
/// <param name="predicate">The predicate.</param>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the invoked action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>The number of items that have been dequeued.</returns>
/// <remarks>
/// <para>
/// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the
/// <paramref name="predicate" /> method
/// filters out items in a way that limits the amount of data passing through.
/// </para>
/// </remarks>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<int> DequeueWhilePredicateWithActionAsync<TState>(
Func<TState, T, bool> predicate,
Action<TState, IEnumerable<T>> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// Tries asynchronously to load the topmost item and execute an action on it, deleting the topmost object data if the
/// operation is successful.
/// </summary>
/// <typeparam name="TState">The type of the state object to send to the action.</typeparam>
/// <param name="predicate">The predicate.</param>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the invoked action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>The number of items that have been dequeued.</returns>
/// <remarks>
/// <para>
/// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the
/// <paramref name="predicate" /> method
/// filters out items in a way that limits the amount of data passing through.
/// </para>
/// </remarks>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<int> DequeueWhilePredicateWithActionAsync<TState>(
Func<TState, T, Task<bool>> predicate,
Action<TState, IEnumerable<T>> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// Tries asynchronously to load the topmost item and execute an action on it, deleting the topmost object data if the
/// operation is successful.
/// </summary>
/// <typeparam name="TState">The type of the state object to send to the action.</typeparam>
/// <param name="predicate">The predicate.</param>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the invoked action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>The number of items that have been dequeued.</returns>
/// <remarks>
/// <para>
/// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the
/// <paramref name="predicate" /> method
/// filters out items in a way that limits the amount of data passing through.
/// </para>
/// </remarks>
ValueTask<int> DequeueWhilePredicateWithActionAsync<TState>(
Func<TState, T, ValueTask<bool>> predicate,
Action<TState, IEnumerable<T>> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// Tries asynchronously to load the topmost item and execute an action on it, deleting the topmost object data if the
/// operation is successful.
/// </summary>
/// <typeparam name="TState">The type of the state object to send to the action.</typeparam>
/// <param name="predicate">The predicate.</param>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the invoked action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>The number of items that have been dequeued.</returns>
/// <remarks>
/// <para>
/// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the
/// <paramref name="predicate" /> method
/// filters out items in a way that limits the amount of data passing through.
/// </para>
/// </remarks>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<int> DequeueWhilePredicateWithActionAsync<TState>(
Func<TState, T, bool> predicate,
Func<TState, IEnumerable<T>, Task> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// Tries asynchronously to load the topmost item and execute an action on it, deleting the topmost object data if the
/// operation is successful.
/// </summary>
/// <typeparam name="TState">The type of the state object to send to the action.</typeparam>
/// <param name="predicate">The predicate.</param>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the invoked action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>The number of items that have been dequeued.</returns>
/// <remarks>
/// <para>
/// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the
/// <paramref name="predicate" /> method
/// filters out items in a way that limits the amount of data passing through.
/// </para>
/// </remarks>
ValueTask<int> DequeueWhilePredicateWithActionAsync<TState>(
Func<TState, T, bool> predicate,
Func<TState, IEnumerable<T>, ValueTask> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// Tries asynchronously to load the topmost item and execute an action on it, deleting the topmost object data if the
/// operation is successful.
/// </summary>
/// <typeparam name="TState">The type of the state object to send to the action.</typeparam>
/// <param name="predicate">The predicate.</param>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the invoked action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>The number of items that have been dequeued.</returns>
/// <remarks>
/// <para>
/// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the
/// <paramref name="predicate" /> method
/// filters out items in a way that limits the amount of data passing through.
/// </para>
/// </remarks>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<int> DequeueWhilePredicateWithActionAsync<TState>(
Func<TState, T, Task<bool>> predicate,
Func<TState, IEnumerable<T>, Task> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// Tries asynchronously to load the topmost item and execute an action on it, deleting the topmost object data if the
/// operation is successful.
/// </summary>
/// <typeparam name="TState">The type of the state object to send to the action.</typeparam>
/// <param name="predicate">The predicate.</param>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the invoked action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>The number of items that have been dequeued.</returns>
/// <remarks>
/// <para>
/// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the
/// <paramref name="predicate" /> method
/// filters out items in a way that limits the amount of data passing through.
/// </para>
/// </remarks>
ValueTask<int> DequeueWhilePredicateWithActionAsync<TState>(
Func<TState, T, ValueTask<bool>> predicate,
Func<TState, IEnumerable<T>, ValueTask> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// De-queues an item from the queue, and executes the specified action on it.
/// </summary>
/// <typeparam name="TState">The type of the state object to pass to the action.</typeparam>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the action.</param>
/// <returns>
/// <see langword="true" /> if the dequeuing is successful, and the action performed, <see langword="false" />
/// otherwise.
/// </returns>
bool DequeueWithAction<TState>(
Action<TState, T> actionToInvoke,
TState state);
/// <summary>
/// Asynchronously de-queues an item from the queue, and executes the specified action on it.
/// </summary>
/// <typeparam name="TState">The type of the state object to pass to the action.</typeparam>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>
/// <see langword="true" /> if the dequeuing is successful, and the action performed, <see langword="false" />
/// otherwise.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<bool> DequeueWithActionAsync<TState>(
Action<TState, T> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// Asynchronously de-queues an item from the queue, and executes the specified action on it.
/// </summary>
/// <typeparam name="TState">The type of the state object to pass to the action.</typeparam>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>
/// <see langword="true" /> if the dequeuing is successful, and the action performed, <see langword="false" />
/// otherwise.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<bool> DequeueWithActionAsync<TState>(
Func<TState, T, Task> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
/// <summary>
/// Asynchronously de-queues an item from the queue, and executes the specified action on it.
/// </summary>
/// <typeparam name="TState">The type of the state object to pass to the action.</typeparam>
/// <param name="actionToInvoke">The action to invoke.</param>
/// <param name="state">The state object to pass to the action.</param>
/// <param name="cancellationToken">The cancellation token for this operation.</param>
/// <returns>
/// <see langword="true" /> if the dequeuing is successful, and the action performed, <see langword="false" />
/// otherwise.
/// </returns>
ValueTask<bool> DequeueWithActionAsync<TState>(
Func<TState, T, ValueTask> actionToInvoke,
TState state,
CancellationToken cancellationToken = default);
#endregion
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Area120.Tables.V1Alpha1.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedTablesServiceClientSnippets
{
/// <summary>Snippet for GetTable</summary>
public void GetTableRequestObject()
{
// Snippet: GetTable(GetTableRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
// Make the request
Table response = tablesServiceClient.GetTable(request);
// End snippet
}
/// <summary>Snippet for GetTableAsync</summary>
public async Task GetTableRequestObjectAsync()
{
// Snippet: GetTableAsync(GetTableRequest, CallSettings)
// Additional: GetTableAsync(GetTableRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
// Make the request
Table response = await tablesServiceClient.GetTableAsync(request);
// End snippet
}
/// <summary>Snippet for GetTable</summary>
public void GetTable()
{
// Snippet: GetTable(string, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string name = "tables/[TABLE]";
// Make the request
Table response = tablesServiceClient.GetTable(name);
// End snippet
}
/// <summary>Snippet for GetTableAsync</summary>
public async Task GetTableAsync()
{
// Snippet: GetTableAsync(string, CallSettings)
// Additional: GetTableAsync(string, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "tables/[TABLE]";
// Make the request
Table response = await tablesServiceClient.GetTableAsync(name);
// End snippet
}
/// <summary>Snippet for GetTable</summary>
public void GetTableResourceNames()
{
// Snippet: GetTable(TableName, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
TableName name = TableName.FromTable("[TABLE]");
// Make the request
Table response = tablesServiceClient.GetTable(name);
// End snippet
}
/// <summary>Snippet for GetTableAsync</summary>
public async Task GetTableResourceNamesAsync()
{
// Snippet: GetTableAsync(TableName, CallSettings)
// Additional: GetTableAsync(TableName, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
TableName name = TableName.FromTable("[TABLE]");
// Make the request
Table response = await tablesServiceClient.GetTableAsync(name);
// End snippet
}
/// <summary>Snippet for ListTables</summary>
public void ListTablesRequestObject()
{
// Snippet: ListTables(ListTablesRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
ListTablesRequest request = new ListTablesRequest { };
// Make the request
PagedEnumerable<ListTablesResponse, Table> response = tablesServiceClient.ListTables(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Table item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTablesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Table item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Table> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Table item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTablesAsync</summary>
public async Task ListTablesRequestObjectAsync()
{
// Snippet: ListTablesAsync(ListTablesRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
ListTablesRequest request = new ListTablesRequest { };
// Make the request
PagedAsyncEnumerable<ListTablesResponse, Table> response = tablesServiceClient.ListTablesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Table item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTablesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Table item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Table> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Table item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetWorkspace</summary>
public void GetWorkspaceRequestObject()
{
// Snippet: GetWorkspace(GetWorkspaceRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
// Make the request
Workspace response = tablesServiceClient.GetWorkspace(request);
// End snippet
}
/// <summary>Snippet for GetWorkspaceAsync</summary>
public async Task GetWorkspaceRequestObjectAsync()
{
// Snippet: GetWorkspaceAsync(GetWorkspaceRequest, CallSettings)
// Additional: GetWorkspaceAsync(GetWorkspaceRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
// Make the request
Workspace response = await tablesServiceClient.GetWorkspaceAsync(request);
// End snippet
}
/// <summary>Snippet for GetWorkspace</summary>
public void GetWorkspace()
{
// Snippet: GetWorkspace(string, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string name = "workspaces/[WORKSPACE]";
// Make the request
Workspace response = tablesServiceClient.GetWorkspace(name);
// End snippet
}
/// <summary>Snippet for GetWorkspaceAsync</summary>
public async Task GetWorkspaceAsync()
{
// Snippet: GetWorkspaceAsync(string, CallSettings)
// Additional: GetWorkspaceAsync(string, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "workspaces/[WORKSPACE]";
// Make the request
Workspace response = await tablesServiceClient.GetWorkspaceAsync(name);
// End snippet
}
/// <summary>Snippet for GetWorkspace</summary>
public void GetWorkspaceResourceNames()
{
// Snippet: GetWorkspace(WorkspaceName, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
WorkspaceName name = WorkspaceName.FromWorkspace("[WORKSPACE]");
// Make the request
Workspace response = tablesServiceClient.GetWorkspace(name);
// End snippet
}
/// <summary>Snippet for GetWorkspaceAsync</summary>
public async Task GetWorkspaceResourceNamesAsync()
{
// Snippet: GetWorkspaceAsync(WorkspaceName, CallSettings)
// Additional: GetWorkspaceAsync(WorkspaceName, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
WorkspaceName name = WorkspaceName.FromWorkspace("[WORKSPACE]");
// Make the request
Workspace response = await tablesServiceClient.GetWorkspaceAsync(name);
// End snippet
}
/// <summary>Snippet for ListWorkspaces</summary>
public void ListWorkspacesRequestObject()
{
// Snippet: ListWorkspaces(ListWorkspacesRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
ListWorkspacesRequest request = new ListWorkspacesRequest { };
// Make the request
PagedEnumerable<ListWorkspacesResponse, Workspace> response = tablesServiceClient.ListWorkspaces(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Workspace item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListWorkspacesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workspace item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workspace> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workspace item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListWorkspacesAsync</summary>
public async Task ListWorkspacesRequestObjectAsync()
{
// Snippet: ListWorkspacesAsync(ListWorkspacesRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
ListWorkspacesRequest request = new ListWorkspacesRequest { };
// Make the request
PagedAsyncEnumerable<ListWorkspacesResponse, Workspace> response = tablesServiceClient.ListWorkspacesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Workspace item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListWorkspacesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workspace item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workspace> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workspace item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetRow</summary>
public void GetRowRequestObject()
{
// Snippet: GetRow(GetRowRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
View = View.Unspecified,
};
// Make the request
Row response = tablesServiceClient.GetRow(request);
// End snippet
}
/// <summary>Snippet for GetRowAsync</summary>
public async Task GetRowRequestObjectAsync()
{
// Snippet: GetRowAsync(GetRowRequest, CallSettings)
// Additional: GetRowAsync(GetRowRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
View = View.Unspecified,
};
// Make the request
Row response = await tablesServiceClient.GetRowAsync(request);
// End snippet
}
/// <summary>Snippet for GetRow</summary>
public void GetRow()
{
// Snippet: GetRow(string, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string name = "tables/[TABLE]/rows/[ROW]";
// Make the request
Row response = tablesServiceClient.GetRow(name);
// End snippet
}
/// <summary>Snippet for GetRowAsync</summary>
public async Task GetRowAsync()
{
// Snippet: GetRowAsync(string, CallSettings)
// Additional: GetRowAsync(string, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "tables/[TABLE]/rows/[ROW]";
// Make the request
Row response = await tablesServiceClient.GetRowAsync(name);
// End snippet
}
/// <summary>Snippet for GetRow</summary>
public void GetRowResourceNames()
{
// Snippet: GetRow(RowName, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
RowName name = RowName.FromTableRow("[TABLE]", "[ROW]");
// Make the request
Row response = tablesServiceClient.GetRow(name);
// End snippet
}
/// <summary>Snippet for GetRowAsync</summary>
public async Task GetRowResourceNamesAsync()
{
// Snippet: GetRowAsync(RowName, CallSettings)
// Additional: GetRowAsync(RowName, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
RowName name = RowName.FromTableRow("[TABLE]", "[ROW]");
// Make the request
Row response = await tablesServiceClient.GetRowAsync(name);
// End snippet
}
/// <summary>Snippet for ListRows</summary>
public void ListRowsRequestObject()
{
// Snippet: ListRows(ListRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
ListRowsRequest request = new ListRowsRequest
{
Parent = "",
View = View.Unspecified,
Filter = "",
};
// Make the request
PagedEnumerable<ListRowsResponse, Row> response = tablesServiceClient.ListRows(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Row item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListRowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Row item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Row> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Row item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRowsAsync</summary>
public async Task ListRowsRequestObjectAsync()
{
// Snippet: ListRowsAsync(ListRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
ListRowsRequest request = new ListRowsRequest
{
Parent = "",
View = View.Unspecified,
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListRowsResponse, Row> response = tablesServiceClient.ListRowsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Row item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListRowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Row item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Row> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Row item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRows</summary>
public void ListRows()
{
// Snippet: ListRows(string, string, int?, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedEnumerable<ListRowsResponse, Row> response = tablesServiceClient.ListRows(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Row item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListRowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Row item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Row> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Row item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRowsAsync</summary>
public async Task ListRowsAsync()
{
// Snippet: ListRowsAsync(string, string, int?, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedAsyncEnumerable<ListRowsResponse, Row> response = tablesServiceClient.ListRowsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Row item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListRowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Row item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Row> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Row item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CreateRow</summary>
public void CreateRowRequestObject()
{
// Snippet: CreateRow(CreateRowRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
CreateRowRequest request = new CreateRowRequest
{
Parent = "",
Row = new Row(),
View = View.Unspecified,
};
// Make the request
Row response = tablesServiceClient.CreateRow(request);
// End snippet
}
/// <summary>Snippet for CreateRowAsync</summary>
public async Task CreateRowRequestObjectAsync()
{
// Snippet: CreateRowAsync(CreateRowRequest, CallSettings)
// Additional: CreateRowAsync(CreateRowRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
CreateRowRequest request = new CreateRowRequest
{
Parent = "",
Row = new Row(),
View = View.Unspecified,
};
// Make the request
Row response = await tablesServiceClient.CreateRowAsync(request);
// End snippet
}
/// <summary>Snippet for CreateRow</summary>
public void CreateRow()
{
// Snippet: CreateRow(string, Row, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string parent = "";
Row row = new Row();
// Make the request
Row response = tablesServiceClient.CreateRow(parent, row);
// End snippet
}
/// <summary>Snippet for CreateRowAsync</summary>
public async Task CreateRowAsync()
{
// Snippet: CreateRowAsync(string, Row, CallSettings)
// Additional: CreateRowAsync(string, Row, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
Row row = new Row();
// Make the request
Row response = await tablesServiceClient.CreateRowAsync(parent, row);
// End snippet
}
/// <summary>Snippet for BatchCreateRows</summary>
public void BatchCreateRowsRequestObject()
{
// Snippet: BatchCreateRows(BatchCreateRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
BatchCreateRowsRequest request = new BatchCreateRowsRequest
{
Parent = "",
Requests =
{
new CreateRowRequest(),
},
};
// Make the request
BatchCreateRowsResponse response = tablesServiceClient.BatchCreateRows(request);
// End snippet
}
/// <summary>Snippet for BatchCreateRowsAsync</summary>
public async Task BatchCreateRowsRequestObjectAsync()
{
// Snippet: BatchCreateRowsAsync(BatchCreateRowsRequest, CallSettings)
// Additional: BatchCreateRowsAsync(BatchCreateRowsRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
BatchCreateRowsRequest request = new BatchCreateRowsRequest
{
Parent = "",
Requests =
{
new CreateRowRequest(),
},
};
// Make the request
BatchCreateRowsResponse response = await tablesServiceClient.BatchCreateRowsAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateRow</summary>
public void UpdateRowRequestObject()
{
// Snippet: UpdateRow(UpdateRowRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
UpdateRowRequest request = new UpdateRowRequest
{
Row = new Row(),
UpdateMask = new FieldMask(),
View = View.Unspecified,
};
// Make the request
Row response = tablesServiceClient.UpdateRow(request);
// End snippet
}
/// <summary>Snippet for UpdateRowAsync</summary>
public async Task UpdateRowRequestObjectAsync()
{
// Snippet: UpdateRowAsync(UpdateRowRequest, CallSettings)
// Additional: UpdateRowAsync(UpdateRowRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateRowRequest request = new UpdateRowRequest
{
Row = new Row(),
UpdateMask = new FieldMask(),
View = View.Unspecified,
};
// Make the request
Row response = await tablesServiceClient.UpdateRowAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateRow</summary>
public void UpdateRow()
{
// Snippet: UpdateRow(Row, FieldMask, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
Row row = new Row();
FieldMask updateMask = new FieldMask();
// Make the request
Row response = tablesServiceClient.UpdateRow(row, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateRowAsync</summary>
public async Task UpdateRowAsync()
{
// Snippet: UpdateRowAsync(Row, FieldMask, CallSettings)
// Additional: UpdateRowAsync(Row, FieldMask, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
Row row = new Row();
FieldMask updateMask = new FieldMask();
// Make the request
Row response = await tablesServiceClient.UpdateRowAsync(row, updateMask);
// End snippet
}
/// <summary>Snippet for BatchUpdateRows</summary>
public void BatchUpdateRowsRequestObject()
{
// Snippet: BatchUpdateRows(BatchUpdateRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
BatchUpdateRowsRequest request = new BatchUpdateRowsRequest
{
Parent = "",
Requests =
{
new UpdateRowRequest(),
},
};
// Make the request
BatchUpdateRowsResponse response = tablesServiceClient.BatchUpdateRows(request);
// End snippet
}
/// <summary>Snippet for BatchUpdateRowsAsync</summary>
public async Task BatchUpdateRowsRequestObjectAsync()
{
// Snippet: BatchUpdateRowsAsync(BatchUpdateRowsRequest, CallSettings)
// Additional: BatchUpdateRowsAsync(BatchUpdateRowsRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
BatchUpdateRowsRequest request = new BatchUpdateRowsRequest
{
Parent = "",
Requests =
{
new UpdateRowRequest(),
},
};
// Make the request
BatchUpdateRowsResponse response = await tablesServiceClient.BatchUpdateRowsAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteRow</summary>
public void DeleteRowRequestObject()
{
// Snippet: DeleteRow(DeleteRowRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
// Make the request
tablesServiceClient.DeleteRow(request);
// End snippet
}
/// <summary>Snippet for DeleteRowAsync</summary>
public async Task DeleteRowRequestObjectAsync()
{
// Snippet: DeleteRowAsync(DeleteRowRequest, CallSettings)
// Additional: DeleteRowAsync(DeleteRowRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
// Make the request
await tablesServiceClient.DeleteRowAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteRow</summary>
public void DeleteRow()
{
// Snippet: DeleteRow(string, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string name = "tables/[TABLE]/rows/[ROW]";
// Make the request
tablesServiceClient.DeleteRow(name);
// End snippet
}
/// <summary>Snippet for DeleteRowAsync</summary>
public async Task DeleteRowAsync()
{
// Snippet: DeleteRowAsync(string, CallSettings)
// Additional: DeleteRowAsync(string, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "tables/[TABLE]/rows/[ROW]";
// Make the request
await tablesServiceClient.DeleteRowAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteRow</summary>
public void DeleteRowResourceNames()
{
// Snippet: DeleteRow(RowName, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
RowName name = RowName.FromTableRow("[TABLE]", "[ROW]");
// Make the request
tablesServiceClient.DeleteRow(name);
// End snippet
}
/// <summary>Snippet for DeleteRowAsync</summary>
public async Task DeleteRowResourceNamesAsync()
{
// Snippet: DeleteRowAsync(RowName, CallSettings)
// Additional: DeleteRowAsync(RowName, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
RowName name = RowName.FromTableRow("[TABLE]", "[ROW]");
// Make the request
await tablesServiceClient.DeleteRowAsync(name);
// End snippet
}
/// <summary>Snippet for BatchDeleteRows</summary>
public void BatchDeleteRowsRequestObject()
{
// Snippet: BatchDeleteRows(BatchDeleteRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
BatchDeleteRowsRequest request = new BatchDeleteRowsRequest
{
ParentAsTableName = TableName.FromTable("[TABLE]"),
RowNames =
{
RowName.FromTableRow("[TABLE]", "[ROW]"),
},
};
// Make the request
tablesServiceClient.BatchDeleteRows(request);
// End snippet
}
/// <summary>Snippet for BatchDeleteRowsAsync</summary>
public async Task BatchDeleteRowsRequestObjectAsync()
{
// Snippet: BatchDeleteRowsAsync(BatchDeleteRowsRequest, CallSettings)
// Additional: BatchDeleteRowsAsync(BatchDeleteRowsRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
BatchDeleteRowsRequest request = new BatchDeleteRowsRequest
{
ParentAsTableName = TableName.FromTable("[TABLE]"),
RowNames =
{
RowName.FromTableRow("[TABLE]", "[ROW]"),
},
};
// Make the request
await tablesServiceClient.BatchDeleteRowsAsync(request);
// End snippet
}
}
}
| |
namespace android.gesture
{
[global::MonoJavaBridge.JavaClass()]
public partial class GestureStore : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static GestureStore()
{
InitJNI();
}
protected GestureStore(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _load3033;
public virtual void load(java.io.InputStream arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._load3033, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._load3033, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _load3034;
public virtual void load(java.io.InputStream arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._load3034, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._load3034, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _save3035;
public virtual void save(java.io.OutputStream arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._save3035, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._save3035, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _save3036;
public virtual void save(java.io.OutputStream arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._save3036, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._save3036, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _hasChanged3037;
public virtual bool hasChanged()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.gesture.GestureStore._hasChanged3037);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._hasChanged3037);
}
internal static global::MonoJavaBridge.MethodId _setOrientationStyle3038;
public virtual void setOrientationStyle(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._setOrientationStyle3038, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._setOrientationStyle3038, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getOrientationStyle3039;
public virtual int getOrientationStyle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.gesture.GestureStore._getOrientationStyle3039);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._getOrientationStyle3039);
}
internal static global::MonoJavaBridge.MethodId _setSequenceType3040;
public virtual void setSequenceType(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._setSequenceType3040, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._setSequenceType3040, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSequenceType3041;
public virtual int getSequenceType()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.gesture.GestureStore._getSequenceType3041);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._getSequenceType3041);
}
internal static global::MonoJavaBridge.MethodId _getGestureEntries3042;
public virtual global::java.util.Set getGestureEntries()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallObjectMethod(this.JvmHandle, global::android.gesture.GestureStore._getGestureEntries3042)) as java.util.Set;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._getGestureEntries3042)) as java.util.Set;
}
internal static global::MonoJavaBridge.MethodId _recognize3043;
public virtual global::java.util.ArrayList recognize(android.gesture.Gesture arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.gesture.GestureStore._recognize3043, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.ArrayList;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._recognize3043, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.ArrayList;
}
internal static global::MonoJavaBridge.MethodId _addGesture3044;
public virtual void addGesture(java.lang.String arg0, android.gesture.Gesture arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._addGesture3044, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._addGesture3044, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _removeGesture3045;
public virtual void removeGesture(java.lang.String arg0, android.gesture.Gesture arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._removeGesture3045, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._removeGesture3045, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _removeEntry3046;
public virtual void removeEntry(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.gesture.GestureStore._removeEntry3046, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._removeEntry3046, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getGestures3047;
public virtual global::java.util.ArrayList getGestures(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.gesture.GestureStore._getGestures3047, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.ArrayList;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._getGestures3047, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.ArrayList;
}
internal static global::MonoJavaBridge.MethodId _GestureStore3048;
public GestureStore() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.gesture.GestureStore.staticClass, global::android.gesture.GestureStore._GestureStore3048);
Init(@__env, handle);
}
public static int SEQUENCE_INVARIANT
{
get
{
return 1;
}
}
public static int SEQUENCE_SENSITIVE
{
get
{
return 2;
}
}
public static int ORIENTATION_INVARIANT
{
get
{
return 1;
}
}
public static int ORIENTATION_SENSITIVE
{
get
{
return 2;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.gesture.GestureStore.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureStore"));
global::android.gesture.GestureStore._load3033 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "load", "(Ljava/io/InputStream;Z)V");
global::android.gesture.GestureStore._load3034 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "load", "(Ljava/io/InputStream;)V");
global::android.gesture.GestureStore._save3035 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "save", "(Ljava/io/OutputStream;Z)V");
global::android.gesture.GestureStore._save3036 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "save", "(Ljava/io/OutputStream;)V");
global::android.gesture.GestureStore._hasChanged3037 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "hasChanged", "()Z");
global::android.gesture.GestureStore._setOrientationStyle3038 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "setOrientationStyle", "(I)V");
global::android.gesture.GestureStore._getOrientationStyle3039 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "getOrientationStyle", "()I");
global::android.gesture.GestureStore._setSequenceType3040 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "setSequenceType", "(I)V");
global::android.gesture.GestureStore._getSequenceType3041 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "getSequenceType", "()I");
global::android.gesture.GestureStore._getGestureEntries3042 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "getGestureEntries", "()Ljava/util/Set;");
global::android.gesture.GestureStore._recognize3043 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "recognize", "(Landroid/gesture/Gesture;)Ljava/util/ArrayList;");
global::android.gesture.GestureStore._addGesture3044 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "addGesture", "(Ljava/lang/String;Landroid/gesture/Gesture;)V");
global::android.gesture.GestureStore._removeGesture3045 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "removeGesture", "(Ljava/lang/String;Landroid/gesture/Gesture;)V");
global::android.gesture.GestureStore._removeEntry3046 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "removeEntry", "(Ljava/lang/String;)V");
global::android.gesture.GestureStore._getGestures3047 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "getGestures", "(Ljava/lang/String;)Ljava/util/ArrayList;");
global::android.gesture.GestureStore._GestureStore3048 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureStore.staticClass, "<init>", "()V");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace metahub.schema
{
public delegate void Trellis_Property_Event(Trellis trellis, Property property);
public class ITrellis_Source
{
public string name;
public Dictionary<string, IProperty_Source> properties;
public string parent;
public string primary_key;
public bool? is_value;
public bool? is_abstract;
public bool? is_interface = false;
public List<string> interfaces = new List<string>();
}
[DebuggerDisplay("Trellis({name})")]
public class Trellis
{
public string name;
public Dictionary<string, Property> core_properties = new Dictionary<string, Property>();
public Dictionary<string, Property> all_properties = new Dictionary<string, Property>();
public Trellis parent;
public uint id;
public Property identity_property;
public Schema space;
// public List<Property> properties = new List<Property>();
public bool is_value = false;
public List<string> events;
public bool is_numeric = false;
List<Trellis> _tree = null;
public bool is_abstract = false;
protected Trellis implementation;
public bool is_interface = false;
public List<Trellis> interfaces = new List<Trellis>();
public object default_value = null;
public bool needs_tick = false;
public event Trellis_Property_Event on_add_property;
public Trellis(string name, Schema space)
{
this.name = name;
this.space = space;
space.trellises[name] = this;
}
public Property add_property(string property_name, IProperty_Source source)
{
Property property = new Property(property_name, source, this);
add_property(property);
return property;
}
public Property add_property(Property property)
{
all_properties[property.name] = property;
core_properties[property.name] = property;
property.trellis = this;
if (on_add_property != null)
on_add_property(this, property);
return property;
}
public Property get_property(string name)
{
return !all_properties.ContainsKey(name) ? null : all_properties[name];
}
public Property get_property_or_error(string name)
{
if (!all_properties.ContainsKey(name))
throw new Exception(this.name + " does not contain a property named " + name + ".");
return all_properties[name];
}
public Property get_property_or_null(string name)
{
if (!all_properties.ContainsKey(name))
return null;
return all_properties[name];
}
public Property get_reference(Trellis rail)
{
return all_properties.Values.First(t => t.other_trellis == rail);
}
public List<Trellis> get_tree()
{
if (_tree == null)
{
var trellis = this;
_tree = new List<Trellis>();
do
{
_tree.Insert(0, trellis);
trellis = trellis.parent;
}
while (trellis != null);
}
return _tree;
}
public bool is_a(Trellis trellis)
{
var current = this;
do
{
if (current == trellis)
return true;
current = current.parent;
}
while (current != null);
return false;
}
public Trellis get_real()
{
return implementation ?? this;
}
public void load_properties(ITrellis_Source source)
{
if (source.properties == null)
return;
foreach (var item in source.properties)
{
add_property(item.Key, item.Value);
}
}
public void initialize1(ITrellis_Source source, Schema space)
{
if (source.is_abstract.HasValue)
is_abstract = source.is_abstract.Value;
if (source.is_interface.HasValue)
is_interface = source.is_interface.Value;
if (source.is_value.HasValue)
is_value = source.is_value.Value;
if (source.parent != null)
{
var trellis = this.space.get_trellis(source.parent);
set_parent(trellis);
}
if (source.primary_key != null)
{
var primary_key = source.primary_key;
if (core_properties.ContainsKey(primary_key))
{
identity_property = core_properties[primary_key];
}
}
else
{
if (parent != null)
{
identity_property = parent.identity_property;
}
else if (core_properties.ContainsKey("id"))
{
identity_property = core_properties["id"];
}
}
// var tree = get_tree();
// int index = 0;
// foreach (var trellis in tree)
// {
// foreach (var property in trellis.core_properties)
// {
//// property.id = index++;
//// properties.Add(property);
//// all_properties[property.name] = property;
// }
// }
if (source.properties != null)
{
foreach (var j in source.properties.Keys)
{
Property property = this.get_property(j);
property.initialize_link1(source.properties[j]);
}
}
}
public void initialize2(ITrellis_Source source)
{
if (!source.is_value.HasValue && parent != null)
is_value = parent.is_value;
if (source.properties != null)
{
foreach (var j in source.properties.Keys)
{
Property property = get_property(j);
property.initialize_link2(source.properties[j]);
}
}
is_numeric = core_properties.Values.Any(p => p.type != Kind.Float && p.type != Kind.Int);
if (source.interfaces != null)
{
interfaces = source.interfaces.Select(i => space.get_trellis(i, true)).ToList();
}
}
void set_parent(Trellis new_parent)
{
this.parent = new_parent;
if (new_parent.is_abstract && !is_abstract && is_value)
{
new_parent.implementation = this;
//foreach (var child_space in schema.root_namespace.children)
//{
// for
//}
foreach (var property in new_parent.core_properties.Values)
{
if (property.other_property != null)
{
property.other_property.other_trellis = this;
property.other_property.other_property = get_property_or_null(property.name);
}
}
}
else
{
foreach (var property in new_parent.all_properties.Values)
{
add_property(property.clone());
}
}
// if (!parent.identity)
// throw new Exception(new Error(parent.name + " needs a primary key when being inherited by " + this.name + "."));
//
// this.identity = parent.identity.map((x) => x.clone(this))
}
public string to_string()
{
return name;
}
public string get_available_name(string key, int start = 0)
{
var result = "";
do
{
result = key;
if (start != 0)
result += start;
++start;
} while (all_properties.ContainsKey(result));
return result;
}
}
}
| |
//
// AudioscrobblerConnection.cs
//
// Author:
// Chris Toshok <toshok@ximian.com>
// Alexander Hixon <hixon.alexander@mediati.org>
// Phil Trimble <philtrimble@gmail.com>
// Andres G. Aragoneses <knocte@gmail.com>
//
// Copyright (C) 2005-2008 Novell, Inc.
// Copyright (C) 2013 Phil Trimble
// Copyright (C) 2013 Andres G. Aragoneses
//
// 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.IO;
using System.Net;
using System.Text;
using System.Timers;
using System.Security.Cryptography;
using System.Web;
using Hyena;
using Hyena.Json;
using Mono.Unix;
using System.Collections.Specialized;
namespace Lastfm
{
public class SubmissionStartEventArgs : EventArgs
{
public SubmissionStartEventArgs (int total_count)
{
TotalCount = total_count;
}
public int TotalCount { get; private set; }
}
public class SubmissionUpdateEventArgs : EventArgs
{
public SubmissionUpdateEventArgs (int update_count)
{
UpdateCount = update_count;
}
public int UpdateCount { get; private set; }
}
public class AudioscrobblerConnection
{
private enum State {
Idle,
NeedTransmit,
Transmitting,
WaitingForResponse
};
private const int TICK_INTERVAL = 2000; /* 2 seconds */
private const int RETRY_SECONDS = 60; /* 60 second delay for transmission retries */
private const int TIME_OUT = 10000; /* 10 seconds timeout for webrequests */
private bool connected = false; /* if we're connected to network or not */
public bool Connected {
get { return connected; }
}
private bool started = false; /* engine has started and was/is connected to AS */
public bool Started {
get { return started; }
}
public event EventHandler<SubmissionStartEventArgs> SubmissionStart;
public event EventHandler<SubmissionUpdateEventArgs> SubmissionUpdate;
public event EventHandler SubmissionEnd;
private System.Timers.Timer timer;
private DateTime next_interval;
private IQueue queue;
private int hard_failures = 0;
private bool now_playing_started;
private LastfmRequest current_now_playing_request;
private LastfmRequest current_scrobble_request;
private IAsyncResult current_async_result;
private State state;
internal AudioscrobblerConnection (IQueue queue)
{
LastfmCore.Account.Updated += AccountUpdated;
state = State.Idle;
this.queue = queue;
}
private void AccountUpdated (object o, EventArgs args)
{
Stop ();
Start ();
}
public void UpdateNetworkState (bool connected)
{
Log.DebugFormat ("Audioscrobbler state: {0}", connected ? "connected" : "disconnected");
this.connected = connected;
}
public void Start ()
{
if (started) {
return;
}
started = true;
hard_failures = 0;
queue.TrackAdded += delegate(object o, EventArgs args) {
StartTransitionHandler ();
};
queue.Load ();
StartTransitionHandler ();
}
private void StartTransitionHandler ()
{
if (!started) {
// Don't run if we're not actually started.
return;
}
if (timer == null) {
timer = new System.Timers.Timer ();
timer.Interval = TICK_INTERVAL;
timer.AutoReset = true;
timer.Elapsed += new ElapsedEventHandler (StateTransitionHandler);
timer.Start ();
} else if (!timer.Enabled) {
timer.Start ();
}
}
public void Stop ()
{
StopTransitionHandler ();
queue.Save ();
started = false;
}
private void StopTransitionHandler ()
{
if (timer != null) {
timer.Stop ();
}
}
private void StateTransitionHandler (object o, ElapsedEventArgs e)
{
// if we're not connected, don't bother doing anything involving the network.
if (!connected) {
return;
}
if ((state == State.Idle || state == State.NeedTransmit) && hard_failures > 2) {
hard_failures = 0;
}
// and address changes in our engine state
switch (state) {
case State.Idle:
if (queue.Any ()) {
state = State.NeedTransmit;
RaiseSubmissionStart (queue.Count);
} else if (current_now_playing_request != null) {
// Now playing info needs to be sent
NowPlaying (current_now_playing_request);
} else {
StopTransitionHandler ();
RaiseSubmissionEnd ();
}
break;
case State.NeedTransmit:
if (DateTime.Now > next_interval) {
TransmitQueue ();
}
break;
case State.Transmitting:
case State.WaitingForResponse:
// nothing here
break;
}
}
private void TransmitQueue ()
{
// save here in case we're interrupted before we complete
// the request. we save it again when we get an OK back
// from the server
queue.Save ();
next_interval = DateTime.MinValue;
if (!connected) {
return;
}
state = State.Transmitting;
current_scrobble_request = new LastfmRequest ("track.scrobble", RequestType.Write, ResponseFormat.Json);
int trackCount = 0;
while (true) {
IQueuedTrack track = queue.GetNextTrack ();
if (track == null ||
// Last.fm can technically handle up to 50 songs in one request
// but let's not use the top limit
trackCount == 40) {
break;
}
try {
current_scrobble_request.AddParameters (GetTrackParameters (track, trackCount));
trackCount++;
} catch (MaxSizeExceededException) {
break;
}
}
Log.DebugFormat ("Last.fm scrobbler sending '{0}'", current_scrobble_request.ToString ());
current_async_result = current_scrobble_request.BeginSend (OnScrobbleResponse, trackCount);
state = State.WaitingForResponse;
if (!(current_async_result.AsyncWaitHandle.WaitOne (TIME_OUT, false))) {
Log.Warning ("Audioscrobbler upload failed", "The request timed out and was aborted", false);
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
hard_failures++;
state = State.Idle;
}
}
private static NameValueCollection GetTrackParameters (IQueuedTrack track, int trackCount)
{
string str_track_number = String.Empty;
if (track.TrackNumber != 0) {
str_track_number = track.TrackNumber.ToString();
}
bool chosen_by_user = (track.TrackAuth.Length == 0);
return new NameValueCollection () {
{ String.Format ("timestamp[{0}]", trackCount), track.StartTime.ToString () },
{ String.Format ("track[{0}]", trackCount), track.Title },
{ String.Format ("artist[{0}]", trackCount), track.Artist },
{ String.Format ("album[{0}]", trackCount), track.Album },
{ String.Format ("trackNumber[{0}]", trackCount), str_track_number },
{ String.Format ("duration[{0}]", trackCount), track.Duration.ToString () },
{ String.Format ("mbid[{0}]", trackCount), track.MusicBrainzId },
{ String.Format ("chosenByUser[{0}]", trackCount), chosen_by_user ? "1" : "0" }
};
}
private void OnScrobbleResponse (IAsyncResult ar)
{
int nb_tracks_scrobbled = 0;
try {
current_scrobble_request.EndSend (ar);
nb_tracks_scrobbled = (int)ar.AsyncState;
} catch (Exception e) {
Log.Error ("Failed to complete the scrobble request", e);
state = State.Idle;
return;
}
JsonObject response = null;
try {
response = current_scrobble_request.GetResponseObject ();
} catch (Exception e) {
Log.Error ("Failed to process the scrobble response", e);
state = State.Idle;
return;
}
var error = current_scrobble_request.GetError ();
if (error == StationError.ServiceOffline || error == StationError.TemporarilyUnavailable) {
Log.WarningFormat ("Lastfm is temporarily unavailable: {0}", (string)response ["message"]);
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
hard_failures++;
state = State.Idle;
return;
}
if (error == StationError.None) {
try {
var scrobbles = (JsonObject)response["scrobbles"];
var scrobbles_attr = (JsonObject)scrobbles["@attr"];
Log.InformationFormat ("Audioscrobbler upload succeeded: {0} accepted, {1} ignored",
scrobbles_attr["accepted"], scrobbles_attr["ignored"]);
if (nb_tracks_scrobbled > 1) {
var scrobble_array = (JsonArray)scrobbles["scrobble"];
foreach (JsonObject scrobbled_track in scrobble_array) {
LogIfIgnored (scrobbled_track);
}
} else {
var scrobbled_track = (JsonObject)scrobbles["scrobble"];
LogIfIgnored (scrobbled_track);
}
} catch (Exception) {
Log.Information ("Audioscrobbler upload succeeded but unknown response received");
Log.Debug ("Response received", response.ToString ());
}
hard_failures = 0;
// we succeeded, pop the elements off our queue
queue.RemoveRange (0, nb_tracks_scrobbled);
queue.Save ();
RaiseSubmissionUpdate (nb_tracks_scrobbled);
} else {
// TODO: If error == StationError.InvalidSessionKey,
// suggest to the user to (re)do the Last.fm authentication.
hard_failures++;
queue.RemoveInvalidTracks ();
}
// if there are still valid tracks in the queue then retransmit on the next interval
state = queue.Any () ? State.NeedTransmit : State.Idle;
}
private void LogIfIgnored (JsonObject scrobbled_track)
{
var ignoredMessage = (JsonObject)scrobbled_track["ignoredMessage"];
if (Convert.ToInt32 (ignoredMessage["code"]) == 0) {
return;
}
var track = (JsonObject)scrobbled_track["track"];
var artist = (JsonObject)scrobbled_track["artist"];
var album = (JsonObject)scrobbled_track["album"];
Log.InformationFormat ("Track {0} - {1} (on {2}) ignored by Last.fm, reason: {3}",
artist["#text"], track["#text"], album["#text"],
ignoredMessage["#text"]);
}
public void NowPlaying (string artist, string title, string album, double duration,
int tracknum)
{
NowPlaying (artist, title, album, duration, tracknum, "");
}
public void NowPlaying (string artist, string title, string album, double duration,
int tracknum, string mbrainzid)
{
if (String.IsNullOrEmpty (artist) || String.IsNullOrEmpty (title) || !connected) {
return;
}
// FIXME: need a lock for this flag
if (now_playing_started) {
return;
}
now_playing_started = true;
string str_track_number = String.Empty;
if (tracknum != 0) {
str_track_number = tracknum.ToString();
}
LastfmRequest request = new LastfmRequest ("track.updateNowPlaying", RequestType.Write, ResponseFormat.Json);
request.AddParameter ("track", title);
request.AddParameter ("artist", artist);
request.AddParameter ("album", album);
request.AddParameter ("trackNumber", str_track_number);
request.AddParameter ("duration", Math.Floor (duration).ToString ());
request.AddParameter ("mbid", mbrainzid);
current_now_playing_request = request;
NowPlaying (current_now_playing_request);
}
private void NowPlaying (LastfmRequest request)
{
try {
request.BeginSend (OnNowPlayingResponse);
}
catch (Exception e) {
Log.Warning ("Audioscrobbler NowPlaying failed",
String.Format("Failed to post NowPlaying: {0}", e), false);
}
}
private void OnNowPlayingResponse (IAsyncResult ar)
{
try {
current_now_playing_request.EndSend (ar);
} catch (Exception e) {
Log.Error ("Failed to complete the NowPlaying request", e);
state = State.Idle;
current_now_playing_request = null;
return;
}
StationError error = current_now_playing_request.GetError ();
// API docs say "Now Playing requests that fail should not be retried".
if (error == StationError.InvalidSessionKey) {
Log.Warning ("Audioscrobbler NowPlaying failed", "Session ID sent was invalid", false);
// TODO: Suggest to the user to (re)do the Last.fm authentication ?
} else if (error != StationError.None) {
Log.WarningFormat ("Audioscrobbler NowPlaying failed: {0}", error.ToString ());
} else {
Log.Debug ("Submitted NowPlaying track to Audioscrobbler");
now_playing_started = false;
}
current_now_playing_request = null;
}
private void RaiseSubmissionStart (int total_count)
{
var handler = SubmissionStart;
if (handler != null) {
handler (this, new SubmissionStartEventArgs (total_count));
}
}
private void RaiseSubmissionUpdate (int update_count)
{
var handler = SubmissionUpdate;
if (handler != null) {
handler (this, new SubmissionUpdateEventArgs (update_count));
}
}
private void RaiseSubmissionEnd ()
{
var handler = SubmissionEnd;
if (handler != null) {
handler (this, null);
}
}
}
}
| |
// 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.Runtime.Serialization.Formatters.Tests;
using Xunit;
using TestAttributes;
[module: Foo]
[module: Complicated(1, Stuff = 2)]
namespace TestAttributes
{
public class FooAttribute : Attribute
{
}
public class ComplicatedAttribute : Attribute
{
public int Stuff
{
get;
set;
}
public int Foo
{
get;
}
public ComplicatedAttribute(int foo)
{
Foo = foo;
}
}
}
namespace System.Reflection.Tests
{
public class ModuleTests
{
public static Module Module => typeof(ModuleTests).Module;
public static Module TestModule => typeof(TestModule.Dummy).Module;
[Fact]
public void TestAssembly()
{
Assert.Equal(Assembly.GetExecutingAssembly(), Module.Assembly);
}
[Fact]
public void ModuleHandle()
{
Assert.Equal(typeof(PointerTests).Module.ModuleHandle, Module.ModuleHandle);
}
[Fact]
public void CustomAttributes()
{
List<CustomAttributeData> customAttributes = Module.CustomAttributes.ToList();
Assert.True(customAttributes.Count >= 2);
CustomAttributeData fooAttribute = customAttributes.Single(a => a.AttributeType == typeof(FooAttribute));
Assert.Equal(typeof(FooAttribute).GetConstructors().First(), fooAttribute.Constructor);
Assert.Equal(0, fooAttribute.ConstructorArguments.Count);
Assert.Equal(0, fooAttribute.NamedArguments.Count);
CustomAttributeData complicatedAttribute = customAttributes.Single(a => a.AttributeType == typeof(ComplicatedAttribute));
Assert.Equal(typeof(ComplicatedAttribute).GetConstructors().First(), complicatedAttribute.Constructor);
Assert.Equal(1, complicatedAttribute.ConstructorArguments.Count);
Assert.Equal(typeof(int), complicatedAttribute.ConstructorArguments[0].ArgumentType);
Assert.Equal(1, (int)complicatedAttribute.ConstructorArguments[0].Value);
Assert.Equal(1, complicatedAttribute.NamedArguments.Count);
Assert.Equal(false, complicatedAttribute.NamedArguments[0].IsField);
Assert.Equal("Stuff", complicatedAttribute.NamedArguments[0].MemberName);
Assert.Equal(typeof(ComplicatedAttribute).GetProperty("Stuff"), complicatedAttribute.NamedArguments[0].MemberInfo);
Assert.Equal(typeof(int), complicatedAttribute.NamedArguments[0].TypedValue.ArgumentType);
Assert.Equal(2, complicatedAttribute.NamedArguments[0].TypedValue.Value);
}
[Fact]
public void FullyQualifiedName()
{
Assert.Equal(Assembly.GetExecutingAssembly().Location, Module.FullyQualifiedName);
}
[Fact]
public void Name()
{
Assert.Equal("system.runtime.tests.dll", Module.Name, ignoreCase: true);
}
[Fact]
public void Equality()
{
Assert.True(Assembly.GetExecutingAssembly().GetModules().First() == Module);
Assert.True(Module.Equals(Assembly.GetExecutingAssembly().GetModules().First()));
}
[Fact]
public void TestGetHashCode()
{
Assert.Equal(Assembly.GetExecutingAssembly().GetModules().First().GetHashCode(), Module.GetHashCode());
}
[Theory]
[InlineData(typeof(ModuleTests))]
[InlineData(typeof(PointerTests))]
[InlineData(typeof(EventInfoTests))]
public void TestGetType(Type type)
{
Assert.Equal(type, Module.GetType(type.FullName, true, true));
}
[Fact]
public void TestToString()
{
Assert.Equal("System.Runtime.Tests.dll", Module.ToString());
}
[Fact]
public void IsDefined_NullType()
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() =>
{
Module.IsDefined(null, false);
});
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Equal("attributeType", ex.ParamName);
}
[Fact]
public void GetField_NullName()
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() =>
{
Module.GetField(null);
});
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Equal("name", ex.ParamName);
ex = Assert.Throws<ArgumentNullException>(() =>
{
Module.GetField(null, 0);
});
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Equal("name", ex.ParamName);
}
[Fact]
public void GetField()
{
FieldInfo testInt = TestModule.GetField("TestInt", BindingFlags.Public | BindingFlags.Static);
Assert.Equal(1, (int)testInt.GetValue(null));
testInt.SetValue(null, 100);
Assert.Equal(100, (int)testInt.GetValue(null));
FieldInfo testLong = TestModule.GetField("TestLong", BindingFlags.NonPublic | BindingFlags.Static);
Assert.Equal(2L, (long)testLong.GetValue(null));
testLong.SetValue(null, 200);
Assert.Equal(200L, (long)testLong.GetValue(null));
}
[Fact]
public void GetFields()
{
List<FieldInfo> fields = TestModule.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).OrderBy(f => f.Name).ToList();
Assert.Equal(2, fields.Count);
Assert.Equal(TestModule.GetField("TestInt"), fields[0]);
Assert.Equal(TestModule.GetField("TestLong", BindingFlags.NonPublic | BindingFlags.Static), fields[1]);
}
public static IEnumerable<object[]> Types =>
Module.GetTypes().Select(t => new object[] { t });
[Theory]
[MemberData(nameof(Types))]
public void ResolveType(Type t)
{
Assert.Equal(t, Module.ResolveType(t.MetadataToken));
}
public static IEnumerable<object[]> BadResolveTypes =>
new[]
{
new object[] { 1234 },
new object[] { typeof(ModuleTests).GetMethod("ResolveType").MetadataToken },
new object[] { typeof(ModuleTests).MetadataToken + 10000 },
};
[Theory]
[MemberData(nameof(BadResolveTypes))]
public void ResolveTypeFail(int token)
{
Assert.ThrowsAny<ArgumentException>(() =>
{
Module.ResolveType(token);
});
}
public static IEnumerable<object[]> Methods =>
Module.GetMethods().Select(m => new object[] { m });
[Theory]
[MemberData(nameof(Methods))]
public void ResolveMethod(MethodInfo t)
{
Assert.Equal(t, Module.ResolveMethod(t.MetadataToken));
}
public static IEnumerable<object[]> BadResolveMethods =>
new[]
{
new object[] { 1234 },
new object[] { typeof(ModuleTests).MetadataToken },
new object[] { typeof(ModuleTests).MetadataToken + 1000 },
};
[Theory]
[MemberData(nameof(BadResolveMethods))]
public void ResolveMethodFail(int token)
{
Assert.ThrowsAny<ArgumentException>(() =>
{
Module.ResolveMethod(token);
});
}
public static IEnumerable<object[]> Fields =>
Module.GetFields().Select(f => new object[] { f });
[Theory]
[MemberData(nameof(Fields))]
public void ResolveField(FieldInfo t)
{
Assert.Equal(t, Module.ResolveField(t.MetadataToken));
}
public static IEnumerable<object[]> BadResolveFields =>
new[]
{
new object[] { 1234 },
new object[] { typeof(ModuleTests).MetadataToken },
new object[] { typeof(ModuleTests).MetadataToken + 1000 },
};
[Theory]
[MemberData(nameof(BadResolveFields))]
public void ResolveFieldFail(int token)
{
Assert.ThrowsAny<ArgumentException>(() =>
{
Module.ResolveField(token);
});
}
public static IEnumerable<object[]> BadResolveStrings =>
new[]
{
new object[] { 1234 },
new object[] { typeof(ModuleTests).MetadataToken },
new object[] { typeof(ModuleTests).MetadataToken + 1000 },
};
[Theory]
[MemberData(nameof(BadResolveStrings))]
public void ResolveStringFail(int token)
{
Assert.ThrowsAny<ArgumentException>(() =>
{
Module.ResolveString(token);
});
}
[Theory]
[MemberData(nameof(Types))]
[MemberData(nameof(Methods))]
[MemberData(nameof(Fields))]
public void ResolveMember(MemberInfo member)
{
Assert.Equal(member, Module.ResolveMember(member.MetadataToken));
}
[Fact]
public void ResolveMethodOfGenericClass()
{
Type t = typeof(Foo<>);
Module mod = t.Module;
MethodInfo method = t.GetMethod("Bar");
MethodBase actual = mod.ResolveMethod(method.MetadataToken);
Assert.Equal(method, actual);
}
[Fact]
public void GetTypes()
{
List<Type> types = TestModule.GetTypes().ToList();
Assert.Equal(1, types.Count);
Assert.Equal("System.Reflection.TestModule.Dummy, System.Reflection.TestModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", types[0].AssemblyQualifiedName);
}
[Fact]
public void SerializeModule()
{
Assert.Equal(TestModule, BinaryFormatterHelpers.Clone(TestModule));
}
}
public class Foo<T>
{
public void Bar(T t)
{
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Management.Automation.Language;
using System.Text;
using System.Text.RegularExpressions;
namespace System.Management.Automation
{
/// <summary>
/// Class describing a PowerShell module...
/// </summary>
[Serializable]
internal class ScriptAnalysis
{
internal static ScriptAnalysis Analyze(string path, ExecutionContext context)
{
ModuleIntrinsics.Tracer.WriteLine("Analyzing path: {0}", path);
try
{
if (Utils.PathIsUnc(path) && (context.CurrentCommandProcessor.CommandRuntime != null))
{
ProgressRecord analysisProgress = new ProgressRecord(0,
Modules.ScriptAnalysisPreparing,
string.Format(CultureInfo.InvariantCulture, Modules.ScriptAnalysisModule, path));
analysisProgress.RecordType = ProgressRecordType.Processing;
// Write the progress using a static source ID so that all
// analysis messages get single-threaded in the progress pane (rather than nesting).
context.CurrentCommandProcessor.CommandRuntime.WriteProgress(typeof(ScriptAnalysis).FullName.GetHashCode(), analysisProgress);
}
}
catch (InvalidOperationException)
{
// This may be called when we are not allowed to write progress,
// So eat the invalid operation
}
string scriptContent = ReadScript(path);
ParseError[] errors;
var moduleAst = (new Parser()).Parse(path, scriptContent, null, out errors, ParseMode.ModuleAnalysis);
// Don't bother analyzing if there are syntax errors (we don't do semantic analysis which would
// detect other errors that we also might choose to ignore, but it's slower.)
if (errors.Length > 0)
return null;
ExportVisitor exportVisitor = new ExportVisitor(forCompletion: false);
moduleAst.Visit(exportVisitor);
var result = new ScriptAnalysis
{
DiscoveredClasses = exportVisitor.DiscoveredClasses,
DiscoveredExports = exportVisitor.DiscoveredExports,
DiscoveredAliases = new Dictionary<string, string>(),
DiscoveredModules = exportVisitor.DiscoveredModules,
DiscoveredCommandFilters = exportVisitor.DiscoveredCommandFilters,
AddsSelfToPath = exportVisitor.AddsSelfToPath
};
if (result.DiscoveredCommandFilters.Count == 0)
{
result.DiscoveredCommandFilters.Add("*");
}
else
{
// Post-process aliases, as they are not exported by default
List<WildcardPattern> patterns = new List<WildcardPattern>();
foreach (string discoveredCommandFilter in result.DiscoveredCommandFilters)
{
patterns.Add(WildcardPattern.Get(discoveredCommandFilter, WildcardOptions.IgnoreCase));
}
foreach (var pair in exportVisitor.DiscoveredAliases)
{
string discoveredAlias = pair.Key;
if (SessionStateUtilities.MatchesAnyWildcardPattern(discoveredAlias, patterns, defaultValue: false))
{
result.DiscoveredAliases[discoveredAlias] = pair.Value;
}
}
}
return result;
}
internal static string ReadScript(string path)
{
using (FileStream readerStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
Encoding defaultEncoding = ClrFacade.GetDefaultEncoding();
Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle;
using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding))
{
return scriptReader.ReadToEnd();
}
}
}
internal List<string> DiscoveredExports { get; set; }
internal Dictionary<string, string> DiscoveredAliases { get; set; }
internal List<RequiredModuleInfo> DiscoveredModules { get; set; }
internal List<string> DiscoveredCommandFilters { get; set; }
internal bool AddsSelfToPath { get; set; }
internal List<TypeDefinitionAst> DiscoveredClasses { get; set; }
}
// Defines the visitor that analyzes a script to determine its exports
// and dependencies.
internal class ExportVisitor : AstVisitor2
{
internal ExportVisitor(bool forCompletion)
{
_forCompletion = forCompletion;
DiscoveredExports = new List<string>();
DiscoveredFunctions = new Dictionary<string, FunctionDefinitionAst>(StringComparer.OrdinalIgnoreCase);
DiscoveredAliases = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
DiscoveredModules = new List<RequiredModuleInfo>();
DiscoveredCommandFilters = new List<string>();
DiscoveredClasses = new List<TypeDefinitionAst>();
}
static ExportVisitor()
{
var nameParam = new ParameterInfo { name = "Name", position = 0 };
var valueParam = new ParameterInfo { name = "Value", position = 1 };
var aliasParameterInfo = new ParameterBindingInfo { parameterInfo = new[] { nameParam, valueParam } };
var functionParam = new ParameterInfo { name = "Function", position = -1 };
var cmdletParam = new ParameterInfo { name = "Cmdlet", position = -1 };
var aliasParam = new ParameterInfo { name = "Alias", position = -1 };
var ipmoParameterInfo = new ParameterBindingInfo { parameterInfo = new[] { nameParam, functionParam, cmdletParam, aliasParam } };
functionParam = new ParameterInfo { name = "Function", position = 0 };
var exportModuleMemberInfo = new ParameterBindingInfo { parameterInfo = new[] { functionParam, cmdletParam, aliasParam } };
s_parameterBindingInfoTable = new Dictionary<string, ParameterBindingInfo>(StringComparer.OrdinalIgnoreCase)
{
{"New-Alias", aliasParameterInfo},
{@"Microsoft.PowerShell.Utility\New-Alias", aliasParameterInfo},
{"Set-Alias", aliasParameterInfo},
{@"Microsoft.PowerShell.Utility\Set-Alias", aliasParameterInfo},
{"nal", aliasParameterInfo},
{"sal", aliasParameterInfo},
{"Import-Module", ipmoParameterInfo},
{@"Microsoft.PowerShell.Core\Import-Module", ipmoParameterInfo},
{"ipmo", ipmoParameterInfo},
{"Export-ModuleMember", exportModuleMemberInfo},
{@"Microsoft.PowerShell.Core\Export-ModuleMember", exportModuleMemberInfo}
};
}
private readonly bool _forCompletion;
internal List<string> DiscoveredExports { get; set; }
internal List<RequiredModuleInfo> DiscoveredModules { get; set; }
internal Dictionary<string, FunctionDefinitionAst> DiscoveredFunctions { get; set; }
internal Dictionary<string, string> DiscoveredAliases { get; set; }
internal List<string> DiscoveredCommandFilters { get; set; }
internal bool AddsSelfToPath { get; set; }
internal List<TypeDefinitionAst> DiscoveredClasses { get; set; }
public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst)
{
DiscoveredClasses.Add(typeDefinitionAst);
return _forCompletion ? AstVisitAction.Continue : AstVisitAction.SkipChildren;
}
// Capture simple function definitions
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
{
// Nested functions are ignored for the purposes of exports, but are still
// recorded for command/parameter completion.
// function Foo-Bar { ... }
var functionName = functionDefinitionAst.Name;
DiscoveredFunctions[functionName] = functionDefinitionAst;
ModuleIntrinsics.Tracer.WriteLine("Discovered function definition: {0}", functionName);
// Check if they've defined any aliases
// function Foo-Bar { [Alias("Alias1", "...")] param() ... }
var functionBody = functionDefinitionAst.Body;
if ((functionBody.ParamBlock != null) && (functionBody.ParamBlock.Attributes != null))
{
foreach (AttributeAst attribute in functionBody.ParamBlock.Attributes)
{
if (attribute.TypeName.GetReflectionAttributeType() == typeof(AliasAttribute))
{
foreach (ExpressionAst aliasAst in attribute.PositionalArguments)
{
var aliasExpression = aliasAst as StringConstantExpressionAst;
if (aliasExpression != null)
{
string alias = aliasExpression.Value;
DiscoveredAliases[alias] = functionName;
ModuleIntrinsics.Tracer.WriteLine("Function defines alias: {0} = {1}", alias, functionName);
}
}
}
}
}
if (_forCompletion)
{
if (Ast.GetAncestorAst<ScriptBlockAst>(functionDefinitionAst).Parent == null)
{
DiscoveredExports.Add(functionName);
}
return AstVisitAction.Continue;
}
DiscoveredExports.Add(functionName);
return AstVisitAction.SkipChildren;
}
// Capture modules that add themselves to the path (so they generally package their functionality
// as loose PS1 files)
public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst)
{
// $env:PATH += "";$psScriptRoot""
if (string.Equals("$env:PATH", assignmentStatementAst.Left.ToString(), StringComparison.OrdinalIgnoreCase) &&
Regex.IsMatch(assignmentStatementAst.Right.ToString(), "\\$psScriptRoot", RegexOptions.IgnoreCase))
{
ModuleIntrinsics.Tracer.WriteLine("Module adds itself to the path.");
AddsSelfToPath = true;
}
return AstVisitAction.SkipChildren;
}
// We skip a bunch of random statements because we can't really be accurate detecting functions/classes etc. that
// are conditionally defined.
public override AstVisitAction VisitIfStatement(IfStatementAst ifStmtAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitForStatement(ForStatementAst forStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitWhileStatement(WhileStatementAst whileStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) { return AstVisitAction.SkipChildren; }
// Visit one the other variations:
// - Dotting scripts
// - Setting aliases
// - Importing modules
// - Exporting module members
public override AstVisitAction VisitCommand(CommandAst commandAst)
{
string commandName =
commandAst.GetCommandName() ??
GetSafeValueVisitor.GetSafeValue(commandAst.CommandElements[0], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) as string;
if (commandName == null)
return AstVisitAction.SkipChildren;
// They are trying to dot a script
if (commandAst.InvocationOperator == TokenKind.Dot)
{
// . Foo-Bar4.ps1
// . $psScriptRoot\Foo-Bar.ps1 -Bing Baz
// . ""$psScriptRoot\Support Files\Foo-Bar2.ps1"" -Bing Baz
// . '$psScriptRoot\Support Files\Foo-Bar3.ps1' -Bing Baz
DiscoveredModules.Add(
new RequiredModuleInfo { Name = commandName, CommandsToPostFilter = new List<string>() });
ModuleIntrinsics.Tracer.WriteLine("Module dots {0}", commandName);
}
// They are setting an alias.
if (string.Equals(commandName, "New-Alias", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "Microsoft.PowerShell.Utility\\New-Alias", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "Set-Alias", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "Microsoft.PowerShell.Utility\\Set-Alias", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "nal", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "sal", StringComparison.OrdinalIgnoreCase))
{
// Set-Alias Foo-Bar5 Foo-Bar
// Set-Alias -Name Foo-Bar6 -Value Foo-Bar
// sal Foo-Bar7 Foo-Bar
// sal -Value Foo-Bar -Name Foo-Bar8
var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);
var name = boundParameters["Name"] as string;
if (!string.IsNullOrEmpty(name))
{
var value = boundParameters["Value"] as string;
if (!string.IsNullOrEmpty(value))
{
// These aren't stored in DiscoveredExports, as they are only
// exported after the user calls Export-ModuleMember.
DiscoveredAliases[name] = value;
ModuleIntrinsics.Tracer.WriteLine("Module defines alias: {0} = {1}", name, value);
}
}
return AstVisitAction.SkipChildren;
}
// They are importing a module
if (string.Equals(commandName, "Import-Module", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "ipmo", StringComparison.OrdinalIgnoreCase))
{
// Import-Module Module1
// Import-Module Module2 -Function Foo-Module2*, Foo-Module2Second* -Cmdlet Foo-Module2Cmdlet,Foo-Module2Cmdlet*
// Import-Module Module3 -Function Foo-Module3Command1, Foo-Module3Command2
// Import-Module Module4,
// Module5
// Import-Module -Name Module6,
// Module7 -Global
var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);
List<string> commandsToPostFilter = new List<string>();
Action<string> onEachCommand = importedCommandName => commandsToPostFilter.Add(importedCommandName);
// Process any exports from the module that we determine from
// the -Function, -Cmdlet, or -Alias parameters
ProcessCmdletArguments(boundParameters["Function"], onEachCommand);
ProcessCmdletArguments(boundParameters["Cmdlet"], onEachCommand);
ProcessCmdletArguments(boundParameters["Alias"], onEachCommand);
// Now, go through all of the discovered modules on Import-Module
// and register them for deeper investigation.
Action<string> onEachModule = moduleName =>
{
ModuleIntrinsics.Tracer.WriteLine("Discovered module import: {0}", moduleName);
DiscoveredModules.Add(
new RequiredModuleInfo
{
Name = moduleName,
CommandsToPostFilter = commandsToPostFilter
});
};
ProcessCmdletArguments(boundParameters["Name"], onEachModule);
return AstVisitAction.SkipChildren;
}
// They are exporting a module member
if (string.Equals(commandName, "Export-ModuleMember", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "Microsoft.PowerShell.Core\\Export-ModuleMember", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "$script:ExportModuleMember", StringComparison.OrdinalIgnoreCase))
{
// Export-ModuleMember *
// Export-ModuleMember Exported-UnNamedModuleMember
// Export-ModuleMember -Function Exported-FunctionModuleMember1, Exported-FunctionModuleMember2 -Cmdlet Exported-CmdletModuleMember `
// -Alias Exported-AliasModuleMember
// & $script:ExportModuleMember -Function (...)
var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);
Action<string> onEachFunction = exportedCommandName =>
{
DiscoveredCommandFilters.Add(exportedCommandName);
ModuleIntrinsics.Tracer.WriteLine("Discovered explicit export: {0}", exportedCommandName);
// If the export doesn't contain wildcards, then add it to the
// discovered commands as well. It is likely that they created
// the command dynamically
if ((!WildcardPattern.ContainsWildcardCharacters(exportedCommandName)) &&
(!DiscoveredExports.Contains(exportedCommandName)))
{
DiscoveredExports.Add(exportedCommandName);
}
};
ProcessCmdletArguments(boundParameters["Function"], onEachFunction);
ProcessCmdletArguments(boundParameters["Cmdlet"], onEachFunction);
Action<string> onEachAlias = exportedAlias =>
{
DiscoveredCommandFilters.Add(exportedAlias);
// If the export doesn't contain wildcards, then add it to the
// discovered commands as well. It is likely that they created
// the command dynamically
if (!WildcardPattern.ContainsWildcardCharacters(exportedAlias))
{
DiscoveredAliases[exportedAlias] = null;
}
};
ProcessCmdletArguments(boundParameters["Alias"], onEachAlias);
return AstVisitAction.SkipChildren;
}
// They are exporting a module member using our advanced 'public' function
// that we've presented in many demos
if ((string.Equals(commandName, "public", StringComparison.OrdinalIgnoreCase)) &&
(commandAst.CommandElements.Count > 2))
{
// public function Publicly-ExportedFunction
// public alias Publicly-ExportedAlias
string publicCommandName = commandAst.CommandElements[2].ToString().Trim();
DiscoveredExports.Add(publicCommandName);
DiscoveredCommandFilters.Add(publicCommandName);
}
return AstVisitAction.SkipChildren;
}
private void ProcessCmdletArguments(object value, Action<string> onEachArgument)
{
if (value == null) return;
var commandName = value as string;
if (commandName != null)
{
onEachArgument(commandName);
return;
}
var names = value as object[];
if (names != null)
{
foreach (var n in names)
{
// This is slightly more permissive than what would really happen with parameter binding
// in that it would allow arrays of arrays in ways that don't actually work
ProcessCmdletArguments(n, onEachArgument);
}
}
}
// This method does parameter binding for a very limited set of scenarios, specifically
// for New-Alias, Set-Alias, Import-Module, and Export-ModuleMember. It might not even
// correctly handle these cmdlets if new parameters are added.
//
// It also only populates the bound parameters for a limited set of parameters needed
// for module analysis.
private static Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string commandName)
{
var result = new Hashtable(StringComparer.OrdinalIgnoreCase);
var parameterBindingInfo = s_parameterBindingInfoTable[commandName].parameterInfo;
int positionsBound = 0;
for (int i = 1; i < commandAst.CommandElements.Count; i++)
{
var element = commandAst.CommandElements[i];
var specifiedParameter = element as CommandParameterAst;
if (specifiedParameter != null)
{
bool boundParameter = false;
var specifiedParamName = specifiedParameter.ParameterName;
foreach (var parameterInfo in parameterBindingInfo)
{
if (parameterInfo.name.StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase))
{
if (parameterInfo.position != -1)
{
positionsBound |= 1 << parameterInfo.position;
}
var argumentAst = specifiedParameter.Argument;
if (argumentAst == null)
{
argumentAst = commandAst.CommandElements[i] as ExpressionAst;
if (argumentAst != null)
{
i += 1;
}
}
if (argumentAst != null)
{
boundParameter = true;
result[parameterInfo.name] =
GetSafeValueVisitor.GetSafeValue(argumentAst, null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis);
}
break;
}
}
if (boundParameter || specifiedParameter.Argument != null)
{
continue;
}
if (!"PassThru".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Force".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Confirm".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Global".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"AsCustomObject".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Verbose".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Debug".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"DisableNameChecking".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"NoClobber".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase))
{
// Named parameter, skip the argument (except for specific switch parameters
i += 1;
}
}
else
{
// Positional argument, find which position we want to bind
int pos = 0;
for (; pos < 10; pos++)
{
if ((positionsBound & (1 << pos)) == 0)
break;
}
positionsBound |= 1 << pos;
// Now see if we care (we probably do, but if the user did something odd, like specify too many, then we don't really)
foreach (var parameterInfo in parameterBindingInfo)
{
if (parameterInfo.position == pos)
{
result[parameterInfo.name] = GetSafeValueVisitor.GetSafeValue(
commandAst.CommandElements[i], null,
GetSafeValueVisitor.SafeValueContext.ModuleAnalysis);
}
}
}
}
return result;
}
private static readonly Dictionary<string, ParameterBindingInfo> s_parameterBindingInfoTable;
private sealed class ParameterBindingInfo
{
internal ParameterInfo[] parameterInfo;
}
private struct ParameterInfo
{
internal string name;
internal int position;
}
}
// Class to keep track of modules we need to import, and commands that should
// be filtered out of them.
[Serializable]
internal class RequiredModuleInfo
{
internal string Name { get; set; }
internal List<string> CommandsToPostFilter { get; set; }
}
}
| |
namespace Volante
{
using System;
using System.Collections.Generic;
using System.Text;
public enum IndexType
{
Unique,
NonUnique
}
public enum TransactionMode
{
/// <summary>
/// Exclusive per-thread transaction: each thread accesses database in exclusive mode
/// </summary>
Exclusive,
/// <summary>
/// Cooperative mode; all threads share the same transaction. Commit will commit changes made
/// by all threads. To make this schema work correctly, it is necessary to ensure (using locking)
/// that no thread is performing update of the database while another one tries to perform commit.
/// Rollback will undo the work of all threads.
/// </summary>
Cooperative,
/// <summary>
/// Serializable per-thread transaction. Unlike exclusive mode, threads can concurrently access database,
/// but effect will be the same as them working exclusively.
/// To provide such behavior, programmer should lock all access objects (or use hierarchical locking).
/// When object is updated, exclusive lock should be set, otherwise shared lock is enough.
/// Lock should be preserved until the end of transaction.
/// </summary>
Serializable,
#if WITH_REPLICATION
/// <summary>
/// Read only transaction which can be started at replication slave node.
/// It runs concurrently with receiving updates from master node.
/// </summary>
ReplicationSlave
#endif
}
public enum CacheType
{
Lru,
Strong,
Weak
}
/// <summary> Object db
/// </summary>
public interface IDatabase
{
/// <summary>Get/set database root. Database can have exactly one root.
/// If you need several root objects and access them by name (as is possible
/// in many other OODBMSes), create an index and use it as root object.
/// Previous reference to the root object is rewritten but old root is not
/// automatically deallocated.
/// </summary>
IPersistent Root { get; set; }
/// <summary>Open the database
/// </summary>
/// <param name="filePath">path to the database file
/// </param>
/// <param name="cacheSizeInBytes">size of database cache, in bytes.
/// Minimum size of the cache should be 64kB (64*1024 bytes).
/// Larger cache usually leads to better performance. If the size is 0
/// the cache is unlimited - and will grow to the size of the database.
/// </param>
void Open(String filePath, int cacheSizeInBytes);
/// <summary>Open the database with default page pool size (4 MB)
/// </summary>
/// <param name="filePath">path to the database file
/// </param>
void Open(String filePath);
/// <summary>Open the db
/// </summary>
/// <param name="file">object implementing IFile interface
/// </param>
/// <param name="cacheSizeInBytes">size of database cache, in bytes.
/// Minimum size of the cache should be 64kB (64*1024 bytes).
/// Larger cache usually leads to better performance. If the size is 0
/// the cache is unlimited - and will grow to the size of the database.
/// </param>
void Open(IFile file, int cacheSizeInBytes);
/// <summary>Open the database with default cache size
/// </summary>
/// <param name="file">user specific implementation of IFile interface
/// </param>
void Open(IFile file);
/// <summary>Check if database is opened
/// </summary>
/// <returns><code>true</code>if database was opened by <code>open</code> method,
/// <code>false</code> otherwise
/// </returns>
bool IsOpened { get; }
/// <summary> Commit changes done by the last transaction. Transaction is started implcitly with forst update
/// opertation.
/// </summary>
void Commit();
/// <summary> Rollback changes made by the last transaction
/// </summary>
void Rollback();
/// <summary>
/// Backup current state of database
/// </summary>
/// <param name="stream">output stream to which backup is done</param>
void Backup(System.IO.Stream stream);
/// <summary> Create new index. K parameter specifies key type, V - associated object type.
/// </summary>
/// <param name="indexType">whether index is unique (duplicate value of keys are not allowed)
/// </param>
/// <returns>persistent object implementing index
/// </returns>
/// <exception cref="Volante.DatabaseException">DatabaseException(DatabaseException.ErrorCode.UNSUPPORTED_INDEX_TYPE) exception if
/// specified key type is not supported by implementation.
/// </exception>
IIndex<K, V> CreateIndex<K, V>(IndexType indexType) where V : class,IPersistent;
/// <summary> Create new thick index (index with large number of duplicated keys).
/// K parameter specifies key type, V - associated object type.
/// </summary>
/// <returns>persistent object implementing thick index
/// </returns>
/// <exception cref="Volante.DatabaseException">DatabaseException(DatabaseException.ErrorCode.UNSUPPORTED_INDEX_TYPE) exception if
/// specified key type is not supported by implementation.
/// </exception>
IIndex<K, V> CreateThickIndex<K, V>() where V : class,IPersistent;
/// <summary>
/// Create new field index
/// K parameter specifies key type, V - associated object type.
/// </summary>
/// <param name="fieldName">name of the index field. Field with such name should be present in specified class <code>type</code>
/// </param>
/// <param name="indexType">whether index is unique (duplicate value of keys are not allowed)
/// </param>
/// <returns>persistent object implementing field index
/// </returns>
/// <exception cref="Volante.DatabaseException">DatabaseException(DatabaseException.INDEXED_FIELD_NOT_FOUND) if there is no such field in specified class,
/// DatabaseException(DatabaseException.UNSUPPORTED_INDEX_TYPE) exception if type of specified field is not supported by implementation
/// </exception>
IFieldIndex<K, V> CreateFieldIndex<K, V>(string fieldName, IndexType indexType) where V : class,IPersistent;
/// <summary>
/// Create new multi-field index
/// </summary>
/// <param name="fieldNames">array of names of the fields. Field with such name should be present in specified class <code>type</code>
/// </param>
/// <param name="indexType">whether index is unique (duplicate value of keys are not allowed)
/// </param>
/// <returns>persistent object implementing field index
/// </returns>
/// <exception cref="Volante.DatabaseException">DatabaseException(DatabaseException.INDEXED_FIELD_NOT_FOUND) if there is no such field in specified class,
/// DatabaseException(DatabaseException.UNSUPPORTED_INDEX_TYPE) exception if type of specified field is not supported by implementation
/// </exception>
IMultiFieldIndex<V> CreateFieldIndex<V>(string[] fieldNames, IndexType indexType) where V : class,IPersistent;
#if WITH_OLD_BTREE
/// <summary>
/// Create new bit index. Bit index is used to select object
/// with specified set of (boolean) properties.
/// </summary>
/// <returns>persistent object implementing bit index</returns>
IBitIndex<T> CreateBitIndex<T>() where T : class,IPersistent;
#endif
/// <summary>
/// Create new spatial index with integer coordinates
/// </summary>
/// <returns>
/// persistent object implementing spatial index
/// </returns>
ISpatialIndex<T> CreateSpatialIndex<T>() where T : class,IPersistent;
/// <summary>
/// Create new R2 spatial index
/// </summary>
/// <returns>
/// persistent object implementing spatial index
/// </returns>
ISpatialIndexR2<T> CreateSpatialIndexR2<T>() where T : class,IPersistent;
/// <summary>
/// Create new sorted collection with specified comparator
/// </summary>
/// <param name="comparator">comparator class specifying order in the collection</param>
/// <param name="indexType"> whether collection is unique (members with the same key value are not allowed)</param>
/// <returns> persistent object implementing sorted collection</returns>
ISortedCollection<K, V> CreateSortedCollection<K, V>(PersistentComparator<K, V> comparator, IndexType indexType) where V : class,IPersistent;
/// <summary>
/// Create new sorted collection. Members of this collections should implement
/// <code>System.IComparable</code> interface and make it possible to compare
/// collection members with each other as well as with serch key.
/// </summary>
/// <param name="indexType"> whether collection is unique (members with the same key value are not allowed)</param>
/// <returns> persistent object implementing sorted collection</returns>
ISortedCollection<K, V> CreateSortedCollection<K, V>(IndexType indexType) where V : class,IPersistent, IComparable<K>, IComparable<V>;
/// <summary>Create set of references to persistent objects.
/// </summary>
/// <returns>empty set, members can be added to the set later.
/// </returns>
ISet<T> CreateSet<T>() where T : class,IPersistent;
/// <summary>Create set of references to persistent objects.
/// </summary>
/// <param name="initialSize">initial size of the set</param>
/// <returns>empty set, members can be added to the set later.
/// </returns>
ISet<T> CreateSet<T>(int initialSize) where T : class,IPersistent;
/// <summary>Create one-to-many link.
/// </summary>
/// <returns>empty link, members can be added to the link later.
/// </returns>
ILink<T> CreateLink<T>() where T : class,IPersistent;
/// <summary>Create one-to-many link with specified initial size.
/// </summary>
/// <param name="initialSize">initial size of the array</param>
/// <returns>empty link with specified size
/// </returns>
ILink<T> CreateLink<T>(int initialSize) where T : class,IPersistent;
/// <summary>Create dynamically extended array of referencess to persistent objects.
/// It is intended to be used in classes using virtual properties to
/// access components of persistent objects.
/// </summary>
/// <returns>new empty array, new members can be added to the array later.
/// </returns>
IPArray<T> CreateArray<T>() where T : class,IPersistent;
/// <summary>Create dynamcially extended array of reference to persistent objects.
/// It is inteded to be used in classes using virtual properties to
/// access components of persistent objects.
/// </summary>
/// <param name="initialSize">initially allocated size of the array</param>
/// <returns>new empty array, new members can be added to the array later.
/// </returns>
IPArray<T> CreateArray<T>(int initialSize) where T : class,IPersistent;
/// <summary> Create relation object. Unlike link which represent embedded relation and stored
/// inside owner object, this Relation object is standalone persisitent object
/// containing references to owner and members of the relation
/// </summary>
/// <param name="owner">owner of the relation
/// </param>
/// <returns>object representing empty relation (relation with specified owner and no members),
/// new members can be added to the link later.
/// </returns>
Relation<M, O> CreateRelation<M, O>(O owner)
where M : class,IPersistent
where O : class,IPersistent;
/// <summary>
/// Create new BLOB. Create object for storing large binary data.
/// </summary>
/// <returns>empty BLOB</returns>
IBlob CreateBlob();
/// <summary>
/// Create new time series object.
/// </summary>
/// <param name="blockSize">number of elements in the block</param>
/// <param name="maxBlockTimeInterval">maximal difference in system ticks (100 nanoseconds) between timestamps
/// of the first and the last elements in a block.
/// If value of this parameter is too small, then most blocks will contains less elements
/// than preallocated.
/// If it is too large, then searching of block will be inefficient, because index search
/// will select a lot of extra blocks which do not contain any element from the
/// specified range.
/// Usually the value of this parameter should be set as
/// (number of elements in block)*(tick interval)*2.
/// Coefficient 2 here is used to compact possible holes in time series.
/// For example, if we collect stocks data, we will have data only for working hours.
/// If number of element in block is 100, time series period is 1 day, then
/// value of maxBlockTimeInterval can be set as 100*(24*60*60*10000000L)*2
/// </param>
/// <returns>new empty time series</returns>
ITimeSeries<T> CreateTimeSeries<T>(int blockSize, long maxBlockTimeInterval) where T : ITimeSeriesTick;
#if WITH_PATRICIA
/// <summary>
/// Create PATRICIA trie (Practical Algorithm To Retrieve Information Coded In Alphanumeric)
/// Tries are a kind of tree where each node holds a common part of one or more keys.
/// PATRICIA trie is one of the many existing variants of the trie, which adds path compression
/// by grouping common sequences of nodes together.
/// This structure provides a very efficient way of storing values while maintaining the lookup time
/// for a key in O(N) in the worst case, where N is the length of the longest key.
/// This structure has it's main use in IP routing software, but can provide an interesting alternative
/// to other structures such as hashtables when memory space is of concern.
/// </summary>
/// <returns>created PATRICIA trie</returns>
IPatriciaTrie<T> CreatePatriciaTrie<T>() where T : class,IPersistent;
#endif
/// <summary> Commit transaction (if needed) and close the db
/// </summary>
void Close();
/// <summary>Explicitly start garbage collection
/// </summary>
/// <returns>number of collected (deallocated) objects</returns>
int Gc();
#if WITH_XML
/// <summary> Export database in XML format
/// </summary>
/// <param name="writer">writer for generated XML document
/// </param>
void ExportXML(System.IO.StreamWriter writer);
/// <summary> Import data from XML file
/// </summary>
/// <param name="reader">XML document reader
/// </param>
void ImportXML(System.IO.StreamReader reader);
#endif
/// <summary>
/// Retrieve object by oid. This method should be used with care because
/// if object is deallocated, its oid can be reused. In this case
/// GetObjectByOid() will return reference to the new object with may be
/// different type.
/// </summary>
/// <param name="oid">object oid</param>
/// <returns>reference to the object with specified oid</returns>
IPersistent GetObjectByOid(int oid);
/// <summary>
/// Explicitly make object peristent. Usually objects are made persistent
/// implicitly using "persistency on reachability approach", but this
/// method allows to do it explicitly. If object is already persistent, execution of
/// this method has no effect.
/// </summary>
/// <param name="obj">object to be made persistent</param>
/// <returns>oid assigned to the object</returns>
int MakePersistent(IPersistent obj);
#if WITH_OLD_BTREE
/// Use aternative implementation of B-Tree (not using direct access to database
/// file pages). This implementation should be used in case of serialized per thread transctions.
/// New implementation of B-Tree will be used instead of old implementation
/// if AlternativeBtree property is set. New B-Tree has incompatible format with
/// old B-Tree, so you could not use old database or XML export file with new indices.
/// Alternative B-Tree is needed to provide serializable transaction (old one could not be used).
/// Also it provides better performance (about 3 times comaring with old implementation) because
/// of object caching. And B-Tree supports keys of user defined types.
/// Default value: false
bool AlternativeBtree { get; set; }
#endif
/// <summary>Set/get kind of object cache.
/// If cache is CacheType.Strong none of the loaded persistent objects
/// can be deallocated from memory by garbage collection.
/// CacheType.Weak and CacheType.Lru both use weak references, so loaded
/// objects can be deallocated. Lru cache can also pin some number of
/// recently used objects for improved performance.
/// Default value: CacheType.Lru
/// </summary>
CacheType CacheKind { get; set; }
/// <summary>Set/get initial size of object index. Bigger values increase
/// initial size of database but reduce number of index reallocations.
/// Default value: 1024
/// </summary>
int ObjectIndexInitSize { get; set; }
/// <summary>Set/get initial size of object cache. Default value: 1319
/// </summary>
int ObjectCacheInitSize { get; set; }
/// <summary>Set/get object allocation bitmap extenstion quantum. Memory
/// is allocated by scanning a bitmap. If there is no hole large enough,
/// then database is extended by this value. It should not be smaller
/// than 64 KB.
/// Default value: 104857 bytes (1 MB)
/// </summary>
long ExtensionQuantum { get; set; }
/// Threshold for initiation of garbage collection.
/// If it is set to the value different from long.MaxValue, GC will be started each time
/// when delta between total size of allocated and deallocated objects exceeds specified threashold OR
/// after reaching end of allocation bitmap in allocator.
/// <summary>Set threshold for initiation of garbage collection. By default garbage
/// collection is disabled (threshold is set to
/// Int64.MaxValue). If it is set to the value different fro
/// Long.MAX_VALUE, GC will be started each time when
/// delta between total size of allocated and deallocated
/// objects exceeds specified threashold OR
/// after reaching end of allocation bitmap in allocator.
/// </summary>
/// <param>delta between total size of allocated and deallocated object since last GC or db opening
/// </param>
/// Default value: long.MaxValue
long GcThreshold { get; set; }
/// <summary>Set/get whether garbage collection is performed in a
/// separate thread in order to not block main application.
/// Default value: false
/// </summary>
bool BackgroundGc { get; set; }
/// <summary>Set/get whether dynamic code generation is used to generate
/// pack/unpack methods for persisted classes.
/// If used, serialization/deserialization of classes that only have public
/// fields will be faster. On the downside, those methods must be generated
/// at startup, increasing startup time.
/// Default value: false
/// </summary>
bool CodeGeneration { get; set; }
#if WITH_REPLICATION
/// Request acknowledgement from slave that it receives all data before transaction
/// commit. If this option is not set, then replication master node just writes
/// data to the socket not warring whether it reaches slave node or not.
/// When this option is set to true, master not will wait during each transaction commit acknowledgement
/// from slave node. This option must be either set or not set at both
/// slave and master nodes. If it is set only on one of this nodes then behavior of
/// the system is unpredicted. This option can be used both in synchronous and asynchronous replication
/// mode. The only difference is that in first case main application thread will be blocked waiting
/// for acknowledgment, while in the asynchronous mode special replication thread will be blocked
/// allowing thread performing commit to proceed.
/// Default value: false
bool ReplicationAck { get; set; }
#endif
/// <summary>Get database file. Should only be used to set FileListener.</summary>
IFile File { get; }
/// <summary>Get/set db listener. You can set <code>null</code> listener.
/// </summary>
DatabaseListener Listener { get; set; }
/// <summary>
/// Set class loader. This class loader will be used to locate classes for
/// loaded class descriptors. If class loader is not specified or
/// it did find the class, then class will be searched in all active assemblies
/// </summary>
IClassLoader Loader { get; set; }
#if CF
/// <summary>
/// Compact.NET framework doesn't allow to get list of assemblies loaded
/// in application domain. Without it I do not know how to locate
/// class from foreign assembly by name.
/// Assembly which creates Database is automatically registered.
/// Other assemblies has to explicitely registered by programmer.
/// </summary>
/// <param name="assembly">registered assembly</param>
void RegisterAssembly(System.Reflection.Assembly assembly);
#else
/// <summary>
/// Create persistent class wrapper. This wrapper will implement virtual properties
/// defined in specified class or interface, performing transparent loading and storing of persistent object
/// </summary>
/// <param name="type">Class or interface type of instantiated object</param>
/// <returns>Wrapper for the specified class, implementing all virtual properties defined
/// in it
/// </returns>
IPersistent CreateClass(Type type);
#endif
/// <summary>
/// Begin per-thread transaction. Three types of per-thread transactions are supported:
/// exclusive, cooperative and serializable. In case of exclusive transaction, only one
/// thread can update the database. In cooperative mode, multiple transaction can work
/// concurrently and commit() method will be invoked only when transactions of all threads
/// are terminated. Serializable transactions can also work concurrently. But unlike
/// cooperative transaction, the threads are isolated from each other. Each thread
/// has its own associated set of modified objects and committing the transaction will cause
/// saving only of these objects to the database.To synchronize access to the objects
/// in case of serializable transaction programmer should use lock methods
/// of IResource interface. Shared lock should be set before read access to any object,
/// and exclusive lock - before write access. Locks will be automatically released when
/// transaction is committed (so programmer should not explicitly invoke unlock method)
/// In this case it is guaranteed that transactions are serializable.
/// It is not possible to use <code>IPersistent.store()</code> method in
/// serializable transactions. That is why it is also not possible to use Index and FieldIndex
/// containers (since them are based on B-Tree and B-Tree directly access database pages
/// and use <code>Store()</code> method to assign oid to inserted object.
/// You should use <code>SortedCollection</code> based on T-Tree instead or alternative
/// B-Tree implemenataion (set AlternativeBtree property).
/// </summary>
/// <param name="mode"><code>TransactionMode.Exclusive</code>, <code>TransactionMode.Cooperative</code>,
/// <code>TransactionMode.ReplicationSlave</code> or <code>TransactionMode.Serializable</code>
/// </param>
void BeginThreadTransaction(TransactionMode mode);
/// <summary>
/// End per-thread transaction started by beginThreadTransaction method.
/// <ul>
/// <li>If transaction is <i>exclusive</i>, this method commits the transaction and
/// allows other thread to proceed.</li><li>
/// If transaction is <i>serializable</i>, this method commits sll changes done by this thread
/// and release all locks set by this thread.</li><li>
/// If transaction is <i>cooperative</i>, this method decrement counter of cooperative
/// transactions and if it becomes zero - commit the work</li></ul>
/// </summary>
void EndThreadTransaction();
/// <summary>
/// End per-thread cooperative transaction with specified maximal delay of transaction
/// commit. When cooperative transaction is ended, data is not immediately committed to the
/// disk (because other cooperative transaction can be active at this moment of time).
/// Instead of it cooperative transaction counter is decremented. Commit is performed
/// only when this counter reaches zero value. But in case of heavy load there can be a lot of
/// requests and so a lot of active cooperative transactions. So transaction counter never reaches zero value.
/// If system crash happens a large amount of work will be lost in this case.
/// To prevent such scenario, it is possible to specify maximal delay of pending transaction commit.
/// In this case when such timeout is expired, new cooperative transaction will be blocked until
/// transaction is committed.
/// </summary>
/// <param name="maxDelay">maximal delay in milliseconds of committing transaction. Please notice, that Volante could
/// not force other threads to commit their cooperative transactions when this timeout is expired. It will only
/// block new cooperative transactions to make it possible to current transaction to complete their work.
/// If <code>maxDelay</code> is 0, current thread will be blocked until all other cooperative trasnaction are also finished
/// and changhes will be committed to the database.
/// </param>
void EndThreadTransaction(int maxDelay);
/// <summary>
/// Rollback per-thread transaction. It is safe to use this method only for exclusive transactions.
/// In case of cooperative transactions, this method rollback results of all transactions.
/// </summary>
void RollbackThreadTransaction();
/// <summary>
/// Get database memory dump. This function returns hashmap which key is classes
/// of stored objects and value - TypeMemoryUsage object which specifies number of instances
/// of particular class in the db and total size of memory used by these instance.
/// Size of internal database structures (object index, memory allocation bitmap) is associated with
/// <code>IDatabase</code> class. Size of class descriptors - with <code>System.Type</code> class.
/// <p>This method traverse the db as garbage collection do - starting from the root object
/// and recursively visiting all reachable objects. So it reports statistic only for visible objects.
/// If total database size is significantly larger than total size of all instances reported
/// by this method, it means that there is garbage in the database. You can explicitly invoke
/// garbage collector in this case.</p>
/// </summary>
Dictionary<Type, TypeMemoryUsage> GetMemoryUsage();
/// <summary>
/// Get total size of all allocated objects in the database
/// </summary>
long UsedSize { get; }
/// <summary>
/// Get size of the database
/// </summary>
long DatabaseSize { get; }
// Internal methods
void deallocateObject(IPersistent obj);
void storeObject(IPersistent obj);
void storeFinalizedObject(IPersistent obj);
void loadObject(IPersistent obj);
void modifyObject(IPersistent obj);
void lockObject(IPersistent obj);
}
}
| |
// <copyright file="ChromiumOptions.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium.Chromium
{
/// <summary>
/// Abstract class to manage options specific to Chromium-based browsers.
/// </summary>
public abstract class ChromiumOptions : DriverOptions
{
private const string ArgumentsChromeOption = "args";
private const string BinaryChromeOption = "binary";
private const string ExtensionsChromeOption = "extensions";
private const string LocalStateChromeOption = "localState";
private const string PreferencesChromeOption = "prefs";
private const string DetachChromeOption = "detach";
private const string DebuggerAddressChromeOption = "debuggerAddress";
private const string ExcludeSwitchesChromeOption = "excludeSwitches";
private const string MinidumpPathChromeOption = "minidumpPath";
private const string MobileEmulationChromeOption = "mobileEmulation";
private const string PerformanceLoggingPreferencesChromeOption = "perfLoggingPrefs";
private const string WindowTypesChromeOption = "windowTypes";
private const string UseSpecCompliantProtocolOption = "w3c";
private bool leaveBrowserRunning;
private bool useSpecCompliantProtocol = true;
private string binaryLocation;
private string debuggerAddress;
private string minidumpPath;
private List<string> arguments = new List<string>();
private List<string> extensionFiles = new List<string>();
private List<string> encodedExtensions = new List<string>();
private List<string> excludedSwitches = new List<string>();
private List<string> windowTypes = new List<string>();
private Dictionary<string, object> additionalChromeOptions = new Dictionary<string, object>();
private Dictionary<string, object> userProfilePreferences;
private Dictionary<string, object> localStatePreferences;
private string mobileEmulationDeviceName;
private ChromiumMobileEmulationDeviceSettings mobileEmulationDeviceSettings;
private ChromiumPerformanceLoggingPreferences perfLoggingPreferences;
/// <summary>
/// Initializes a new instance of the <see cref="ChromiumOptions"/> class.
/// </summary>
public ChromiumOptions() : base()
{
this.AddKnownCapabilityName(this.CapabilityName, "current ChromiumOptions class instance");
this.AddKnownCapabilityName(CapabilityType.LoggingPreferences, "SetLoggingPreference method");
this.AddKnownCapabilityName(this.LoggingPreferencesChromeOption, "SetLoggingPreference method");
this.AddKnownCapabilityName(ChromiumOptions.ArgumentsChromeOption, "AddArguments method");
this.AddKnownCapabilityName(ChromiumOptions.BinaryChromeOption, "BinaryLocation property");
this.AddKnownCapabilityName(ChromiumOptions.ExtensionsChromeOption, "AddExtensions method");
this.AddKnownCapabilityName(ChromiumOptions.LocalStateChromeOption, "AddLocalStatePreference method");
this.AddKnownCapabilityName(ChromiumOptions.PreferencesChromeOption, "AddUserProfilePreference method");
this.AddKnownCapabilityName(ChromiumOptions.DetachChromeOption, "LeaveBrowserRunning property");
this.AddKnownCapabilityName(ChromiumOptions.DebuggerAddressChromeOption, "DebuggerAddress property");
this.AddKnownCapabilityName(ChromiumOptions.ExcludeSwitchesChromeOption, "AddExcludedArgument property");
this.AddKnownCapabilityName(ChromiumOptions.MinidumpPathChromeOption, "MinidumpPath property");
this.AddKnownCapabilityName(ChromiumOptions.MobileEmulationChromeOption, "EnableMobileEmulation method");
this.AddKnownCapabilityName(ChromiumOptions.PerformanceLoggingPreferencesChromeOption, "PerformanceLoggingPreferences property");
this.AddKnownCapabilityName(ChromiumOptions.WindowTypesChromeOption, "AddWindowTypes method");
this.AddKnownCapabilityName(ChromiumOptions.UseSpecCompliantProtocolOption, "UseSpecCompliantProtocol property");
}
/// <summary>
/// Gets the vendor prefix to apply to Chromium-specific capability names.
/// </summary>
protected abstract string VendorPrefix { get; }
private string LoggingPreferencesChromeOption
{
get { return this.VendorPrefix + ":loggingPrefs"; }
}
/// <summary>
/// Gets the name of the capability used to store Chromium options in
/// an <see cref="ICapabilities"/> object.
/// </summary>
public abstract string CapabilityName { get; }
/// <summary>
/// Gets or sets the location of the Chromium browser's binary executable file.
/// </summary>
public string BinaryLocation
{
get { return this.binaryLocation; }
set { this.binaryLocation = value; }
}
/// <summary>
/// Gets or sets a value indicating whether Chromium should be left running after the
/// ChromeDriver instance is exited. Defaults to <see langword="false"/>.
/// </summary>
public bool LeaveBrowserRunning
{
get { return this.leaveBrowserRunning; }
set { this.leaveBrowserRunning = value; }
}
/// <summary>
/// Gets the list of arguments appended to the Chromium command line as a string array.
/// </summary>
public ReadOnlyCollection<string> Arguments
{
get { return this.arguments.AsReadOnly(); }
}
/// <summary>
/// Gets the list of extensions to be installed as an array of base64-encoded strings.
/// </summary>
public ReadOnlyCollection<string> Extensions
{
get
{
List<string> allExtensions = new List<string>(this.encodedExtensions);
foreach (string extensionFile in this.extensionFiles)
{
byte[] extensionByteArray = File.ReadAllBytes(extensionFile);
string encodedExtension = Convert.ToBase64String(extensionByteArray);
allExtensions.Add(encodedExtension);
}
return allExtensions.AsReadOnly();
}
}
/// <summary>
/// Gets or sets the address of a Chromium debugger server to connect to.
/// Should be of the form "{hostname|IP address}:port".
/// </summary>
public string DebuggerAddress
{
get { return this.debuggerAddress; }
set { this.debuggerAddress = value; }
}
/// <summary>
/// Gets or sets the directory in which to store minidump files.
/// </summary>
public string MinidumpPath
{
get { return this.minidumpPath; }
set { this.minidumpPath = value; }
}
/// <summary>
/// Gets or sets the performance logging preferences for the driver.
/// </summary>
public ChromiumPerformanceLoggingPreferences PerformanceLoggingPreferences
{
get { return this.perfLoggingPreferences; }
set { this.perfLoggingPreferences = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="ChromiumDriver"/> instance
/// should use the legacy OSS protocol dialect or a dialect compliant with the W3C
/// WebDriver Specification.
/// </summary>
public bool UseSpecCompliantProtocol
{
get { return this.useSpecCompliantProtocol; }
set { this.useSpecCompliantProtocol = value; }
}
/// <summary>
/// Adds a single argument to the list of arguments to be appended to the browser executable command line.
/// </summary>
/// <param name="argument">The argument to add.</param>
public void AddArgument(string argument)
{
if (string.IsNullOrEmpty(argument))
{
throw new ArgumentException("argument must not be null or empty", "argument");
}
this.AddArguments(argument);
}
/// <summary>
/// Adds arguments to be appended to the browser executable command line.
/// </summary>
/// <param name="argumentsToAdd">An array of arguments to add.</param>
public void AddArguments(params string[] argumentsToAdd)
{
this.AddArguments(new List<string>(argumentsToAdd));
}
/// <summary>
/// Adds arguments to be appended to the browser executable command line.
/// </summary>
/// <param name="argumentsToAdd">An <see cref="IEnumerable{T}"/> object of arguments to add.</param>
public void AddArguments(IEnumerable<string> argumentsToAdd)
{
if (argumentsToAdd == null)
{
throw new ArgumentNullException("argumentsToAdd", "argumentsToAdd must not be null");
}
this.arguments.AddRange(argumentsToAdd);
}
/// <summary>
/// Adds a single argument to be excluded from the list of arguments passed by default
/// to the browser executable command line by chromedriver.exe.
/// </summary>
/// <param name="argument">The argument to exclude.</param>
public void AddExcludedArgument(string argument)
{
if (string.IsNullOrEmpty(argument))
{
throw new ArgumentException("argument must not be null or empty", "argument");
}
this.AddExcludedArguments(argument);
}
/// <summary>
/// Adds arguments to be excluded from the list of arguments passed by default
/// to the browser executable command line by chromedriver.exe.
/// </summary>
/// <param name="argumentsToExclude">An array of arguments to exclude.</param>
public void AddExcludedArguments(params string[] argumentsToExclude)
{
this.AddExcludedArguments(new List<string>(argumentsToExclude));
}
/// <summary>
/// Adds arguments to be excluded from the list of arguments passed by default
/// to the browser executable command line by chromedriver.exe.
/// </summary>
/// <param name="argumentsToExclude">An <see cref="IEnumerable{T}"/> object of arguments to exclude.</param>
public void AddExcludedArguments(IEnumerable<string> argumentsToExclude)
{
if (argumentsToExclude == null)
{
throw new ArgumentNullException("argumentsToExclude", "argumentsToExclude must not be null");
}
this.excludedSwitches.AddRange(argumentsToExclude);
}
/// <summary>
/// Adds a path to a packed Chrome extension (.crx file) to the list of extensions
/// to be installed in the instance of Chrome.
/// </summary>
/// <param name="pathToExtension">The full path to the extension to add.</param>
public void AddExtension(string pathToExtension)
{
if (string.IsNullOrEmpty(pathToExtension))
{
throw new ArgumentException("pathToExtension must not be null or empty", "pathToExtension");
}
this.AddExtensions(pathToExtension);
}
/// <summary>
/// Adds a list of paths to packed Chrome extensions (.crx files) to be installed
/// in the instance of Chrome.
/// </summary>
/// <param name="extensions">An array of full paths to the extensions to add.</param>
public void AddExtensions(params string[] extensions)
{
this.AddExtensions(new List<string>(extensions));
}
/// <summary>
/// Adds a list of paths to packed Chrome extensions (.crx files) to be installed
/// in the instance of Chrome.
/// </summary>
/// <param name="extensions">An <see cref="IEnumerable{T}"/> of full paths to the extensions to add.</param>
public void AddExtensions(IEnumerable<string> extensions)
{
if (extensions == null)
{
throw new ArgumentNullException("extensions", "extensions must not be null");
}
foreach (string extension in extensions)
{
if (!File.Exists(extension))
{
throw new FileNotFoundException("No extension found at the specified path", extension);
}
this.extensionFiles.Add(extension);
}
}
/// <summary>
/// Adds a base64-encoded string representing a Chrome extension to the list of extensions
/// to be installed in the instance of Chrome.
/// </summary>
/// <param name="extension">A base64-encoded string representing the extension to add.</param>
public void AddEncodedExtension(string extension)
{
if (string.IsNullOrEmpty(extension))
{
throw new ArgumentException("extension must not be null or empty", "extension");
}
this.AddEncodedExtensions(extension);
}
/// <summary>
/// Adds a list of base64-encoded strings representing Chrome extensions to the list of extensions
/// to be installed in the instance of Chrome.
/// </summary>
/// <param name="extensions">An array of base64-encoded strings representing the extensions to add.</param>
public void AddEncodedExtensions(params string[] extensions)
{
this.AddEncodedExtensions(new List<string>(extensions));
}
/// <summary>
/// Adds a list of base64-encoded strings representing Chrome extensions to be installed
/// in the instance of Chrome.
/// </summary>
/// <param name="extensions">An <see cref="IEnumerable{T}"/> of base64-encoded strings
/// representing the extensions to add.</param>
public void AddEncodedExtensions(IEnumerable<string> extensions)
{
if (extensions == null)
{
throw new ArgumentNullException("extensions", "extensions must not be null");
}
foreach (string extension in extensions)
{
// Run the extension through the base64 converter to test that the
// string is not malformed.
try
{
Convert.FromBase64String(extension);
}
catch (FormatException ex)
{
throw new WebDriverException("Could not properly decode the base64 string", ex);
}
this.encodedExtensions.Add(extension);
}
}
/// <summary>
/// Adds a preference for the user-specific profile or "user data directory."
/// If the specified preference already exists, it will be overwritten.
/// </summary>
/// <param name="preferenceName">The name of the preference to set.</param>
/// <param name="preferenceValue">The value of the preference to set.</param>
public void AddUserProfilePreference(string preferenceName, object preferenceValue)
{
if (this.userProfilePreferences == null)
{
this.userProfilePreferences = new Dictionary<string, object>();
}
this.userProfilePreferences[preferenceName] = preferenceValue;
}
/// <summary>
/// Adds a preference for the local state file in the user's data directory for Chromium.
/// If the specified preference already exists, it will be overwritten.
/// </summary>
/// <param name="preferenceName">The name of the preference to set.</param>
/// <param name="preferenceValue">The value of the preference to set.</param>
public void AddLocalStatePreference(string preferenceName, object preferenceValue)
{
if (this.localStatePreferences == null)
{
this.localStatePreferences = new Dictionary<string, object>();
}
this.localStatePreferences[preferenceName] = preferenceValue;
}
/// <summary>
/// Allows the Chromium browser to emulate a mobile device.
/// </summary>
/// <param name="deviceName">The name of the device to emulate. The device name must be a
/// valid device name from the Chrome DevTools Emulation panel.</param>
/// <remarks>Specifying an invalid device name will not throw an exeption, but
/// will generate an error in Chrome when the driver starts. To unset mobile
/// emulation, call this method with <see langword="null"/> as the argument.</remarks>
public void EnableMobileEmulation(string deviceName)
{
this.mobileEmulationDeviceSettings = null;
this.mobileEmulationDeviceName = deviceName;
}
/// <summary>
/// Allows the Chromium browser to emulate a mobile device.
/// </summary>
/// <param name="deviceSettings">The <see cref="ChromiumMobileEmulationDeviceSettings"/>
/// object containing the settings of the device to emulate.</param>
/// <exception cref="ArgumentException">Thrown if the device settings option does
/// not have a user agent string set.</exception>
/// <remarks>Specifying an invalid device name will not throw an exeption, but
/// will generate an error in Chrome when the driver starts. To unset mobile
/// emulation, call this method with <see langword="null"/> as the argument.</remarks>
public void EnableMobileEmulation(ChromiumMobileEmulationDeviceSettings deviceSettings)
{
this.mobileEmulationDeviceName = null;
if (deviceSettings != null && string.IsNullOrEmpty(deviceSettings.UserAgent))
{
throw new ArgumentException("Device settings must include a user agent string.", "deviceSettings");
}
this.mobileEmulationDeviceSettings = deviceSettings;
}
/// <summary>
/// Adds a type of window that will be listed in the list of window handles
/// returned by the Chrome driver.
/// </summary>
/// <param name="windowType">The name of the window type to add.</param>
/// <remarks>This method can be used to allow the driver to access {webview}
/// elements by adding "webview" as a window type.</remarks>
public void AddWindowType(string windowType)
{
if (string.IsNullOrEmpty(windowType))
{
throw new ArgumentException("windowType must not be null or empty", "windowType");
}
this.AddWindowTypes(windowType);
}
/// <summary>
/// Adds a list of window types that will be listed in the list of window handles
/// returned by the Chromium driver.
/// </summary>
/// <param name="windowTypesToAdd">An array of window types to add.</param>
public void AddWindowTypes(params string[] windowTypesToAdd)
{
this.AddWindowTypes(new List<string>(windowTypesToAdd));
}
/// <summary>
/// Adds a list of window types that will be listed in the list of window handles
/// returned by the Chromium driver.
/// </summary>
/// <param name="windowTypesToAdd">An <see cref="IEnumerable{T}"/> of window types to add.</param>
public void AddWindowTypes(IEnumerable<string> windowTypesToAdd)
{
if (windowTypesToAdd == null)
{
throw new ArgumentNullException("windowTypesToAdd", "windowTypesToAdd must not be null");
}
this.windowTypes.AddRange(windowTypesToAdd);
}
/// <summary>
/// Provides a means to add additional capabilities not yet added as type safe options
/// for the Chromium driver.
/// </summary>
/// <param name="optionName">The name of the capability to add.</param>
/// <param name="optionValue">The value of the capability to add.</param>
/// <exception cref="ArgumentException">
/// thrown when attempting to add a capability for which there is already a type safe option, or
/// when <paramref name="optionName"/> is <see langword="null"/> or the empty string.
/// </exception>
/// <remarks>Calling <see cref="AddAdditionalChromeOption(string, object)"/>
/// where <paramref name="optionName"/> has already been added will overwrite the
/// existing value with the new value in <paramref name="optionValue"/>.
/// Calling this method adds capabilities to the Chrome-specific options object passed to
/// webdriver executable (property name 'goog:chromeOptions').</remarks>
public void AddAdditionalChromeOption(string optionName, object optionValue)
{
this.ValidateCapabilityName(optionName);
this.additionalChromeOptions[optionName] = optionValue;
}
/// <summary>
/// Provides a means to add additional capabilities not yet added as type safe options
/// for the Chromium driver.
/// </summary>
/// <param name="capabilityName">The name of the capability to add.</param>
/// <param name="capabilityValue">The value of the capability to add.</param>
/// <exception cref="ArgumentException">
/// thrown when attempting to add a capability for which there is already a type safe option, or
/// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string.
/// </exception>
/// <remarks>Calling <see cref="AddAdditionalCapability(string, object)"/>
/// where <paramref name="capabilityName"/> has already been added will overwrite the
/// existing value with the new value in <paramref name="capabilityValue"/>.
/// Also, by default, calling this method adds capabilities to the options object passed to
/// chromedriver.exe.</remarks>
[Obsolete("Use the temporary AddAdditionalOption method or the AddAdditionalChromeOption method for adding additional options")]
public override void AddAdditionalCapability(string capabilityName, object capabilityValue)
{
// Add the capability to the chromeOptions object by default. This is to handle
// the 80% case where the chromedriver team adds a new option in chromedriver.exe
// and the bindings have not yet had a type safe option added.
this.AddAdditionalCapability(capabilityName, capabilityValue, false);
}
/// <summary>
/// Provides a means to add additional capabilities not yet added as type safe options
/// for the Chromium driver.
/// </summary>
/// <param name="capabilityName">The name of the capability to add.</param>
/// <param name="capabilityValue">The value of the capability to add.</param>
/// <param name="isGlobalCapability">Indicates whether the capability is to be set as a global
/// capability for the driver instead of a Chromium-specific option.</param>
/// <exception cref="ArgumentException">
/// thrown when attempting to add a capability for which there is already a type safe option, or
/// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string.
/// </exception>
/// <remarks>Calling <see cref="AddAdditionalCapability(string, object, bool)"/>
/// where <paramref name="capabilityName"/> has already been added will overwrite the
/// existing value with the new value in <paramref name="capabilityValue"/></remarks>
[Obsolete("Use the temporary AddAdditionalOption method or the AddAdditionalChromeOption method for adding additional options")]
public void AddAdditionalCapability(string capabilityName, object capabilityValue, bool isGlobalCapability)
{
if (isGlobalCapability)
{
this.AddAdditionalOption(capabilityName, capabilityValue);
}
else
{
this.AddAdditionalChromeOption(capabilityName, capabilityValue);
}
}
/// <summary>
/// Returns DesiredCapabilities for Chromium with these options included as
/// capabilities. This does not copy the options. Further changes will be
/// reflected in the returned capabilities.
/// </summary>
/// <returns>The DesiredCapabilities for Chrome with these options.</returns>
public override ICapabilities ToCapabilities()
{
Dictionary<string, object> chromeOptions = this.BuildChromeOptionsDictionary();
IWritableCapabilities capabilities = this.GenerateDesiredCapabilities(false);
capabilities.SetCapability(this.CapabilityName, chromeOptions);
AddVendorSpecificChromiumCapabilities(capabilities);
Dictionary<string, object> loggingPreferences = this.GenerateLoggingPreferencesDictionary();
if (loggingPreferences != null)
{
capabilities.SetCapability(LoggingPreferencesChromeOption, loggingPreferences);
}
return capabilities.AsReadOnly();
}
/// <summary>
/// Adds vendor-specific capabilities for Chromium-based browsers.
/// </summary>
/// <param name="capabilities">The capabilities to add.</param>
protected virtual void AddVendorSpecificChromiumCapabilities(IWritableCapabilities capabilities)
{
}
private Dictionary<string, object> BuildChromeOptionsDictionary()
{
Dictionary<string, object> chromeOptions = new Dictionary<string, object>();
if (this.Arguments.Count > 0)
{
chromeOptions[ArgumentsChromeOption] = this.Arguments;
}
if (!string.IsNullOrEmpty(this.binaryLocation))
{
chromeOptions[BinaryChromeOption] = this.binaryLocation;
}
ReadOnlyCollection<string> extensions = this.Extensions;
if (extensions.Count > 0)
{
chromeOptions[ExtensionsChromeOption] = extensions;
}
if (this.localStatePreferences != null && this.localStatePreferences.Count > 0)
{
chromeOptions[LocalStateChromeOption] = this.localStatePreferences;
}
if (this.userProfilePreferences != null && this.userProfilePreferences.Count > 0)
{
chromeOptions[PreferencesChromeOption] = this.userProfilePreferences;
}
if (this.leaveBrowserRunning)
{
chromeOptions[DetachChromeOption] = this.leaveBrowserRunning;
}
if (!this.useSpecCompliantProtocol)
{
chromeOptions[UseSpecCompliantProtocolOption] = this.useSpecCompliantProtocol;
}
if (!string.IsNullOrEmpty(this.debuggerAddress))
{
chromeOptions[DebuggerAddressChromeOption] = this.debuggerAddress;
}
if (this.excludedSwitches.Count > 0)
{
chromeOptions[ExcludeSwitchesChromeOption] = this.excludedSwitches;
}
if (!string.IsNullOrEmpty(this.minidumpPath))
{
chromeOptions[MinidumpPathChromeOption] = this.minidumpPath;
}
if (!string.IsNullOrEmpty(this.mobileEmulationDeviceName) || this.mobileEmulationDeviceSettings != null)
{
chromeOptions[MobileEmulationChromeOption] = this.GenerateMobileEmulationSettingsDictionary();
}
if (this.perfLoggingPreferences != null)
{
chromeOptions[PerformanceLoggingPreferencesChromeOption] = this.GeneratePerformanceLoggingPreferencesDictionary();
}
if (this.windowTypes.Count > 0)
{
chromeOptions[WindowTypesChromeOption] = this.windowTypes;
}
foreach (KeyValuePair<string, object> pair in this.additionalChromeOptions)
{
chromeOptions.Add(pair.Key, pair.Value);
}
return chromeOptions;
}
private Dictionary<string, object> GeneratePerformanceLoggingPreferencesDictionary()
{
Dictionary<string, object> perfLoggingPrefsDictionary = new Dictionary<string, object>();
perfLoggingPrefsDictionary["enableNetwork"] = this.perfLoggingPreferences.IsCollectingNetworkEvents;
perfLoggingPrefsDictionary["enablePage"] = this.perfLoggingPreferences.IsCollectingPageEvents;
string tracingCategories = this.perfLoggingPreferences.TracingCategories;
if (!string.IsNullOrEmpty(tracingCategories))
{
perfLoggingPrefsDictionary["traceCategories"] = tracingCategories;
}
perfLoggingPrefsDictionary["bufferUsageReportingInterval"] = Convert.ToInt64(this.perfLoggingPreferences.BufferUsageReportingInterval.TotalMilliseconds);
return perfLoggingPrefsDictionary;
}
private Dictionary<string, object> GenerateMobileEmulationSettingsDictionary()
{
Dictionary<string, object> mobileEmulationSettings = new Dictionary<string, object>();
if (!string.IsNullOrEmpty(this.mobileEmulationDeviceName))
{
mobileEmulationSettings["deviceName"] = this.mobileEmulationDeviceName;
}
else if (this.mobileEmulationDeviceSettings != null)
{
mobileEmulationSettings["userAgent"] = this.mobileEmulationDeviceSettings.UserAgent;
Dictionary<string, object> deviceMetrics = new Dictionary<string, object>();
deviceMetrics["width"] = this.mobileEmulationDeviceSettings.Width;
deviceMetrics["height"] = this.mobileEmulationDeviceSettings.Height;
deviceMetrics["pixelRatio"] = this.mobileEmulationDeviceSettings.PixelRatio;
if (!this.mobileEmulationDeviceSettings.EnableTouchEvents)
{
deviceMetrics["touch"] = this.mobileEmulationDeviceSettings.EnableTouchEvents;
}
mobileEmulationSettings["deviceMetrics"] = deviceMetrics;
}
return mobileEmulationSettings;
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:41 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext
{
#region Loader
/// <summary>
/// <p><see cref="Ext.Loader">Ext.Loader</see> is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
/// via the <see cref="Ext.ExtContext.require">Ext.require</see> shorthand. <see cref="Ext.Loader">Ext.Loader</see> supports both asynchronous and synchronous loading
/// approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:</p>
/// <h1>Asynchronous Loading</h1>
/// <ul>
/// <li><p>Advantages:</p>
/// <ul>
/// <li>Cross-domain</li>
/// <li>No web server needed: you can run the application via the file system protocol (i.e: <code>file://path/to/your/index
/// .html</code>)</li>
/// <li>Best possible debugging experience: error messages come with the exact file name and line number</li>
/// </ul>
/// </li>
/// <li><p>Disadvantages:</p>
/// <ul>
/// <li>Dependencies need to be specified before-hand</li>
/// </ul>
/// </li>
/// </ul>
/// <h3>Method 1: Explicitly include what you need:</h3>
/// <pre><code>// Syntax
/// <see cref="Ext.ExtContext.require">Ext.require</see>({String/Array} expressions);
/// // Example: Single alias
/// <see cref="Ext.ExtContext.require">Ext.require</see>('widget.window');
/// // Example: Single class name
/// <see cref="Ext.ExtContext.require">Ext.require</see>('<see cref="Ext.window.Window">Ext.window.Window</see>');
/// // Example: Multiple aliases / class names mix
/// <see cref="Ext.ExtContext.require">Ext.require</see>(['widget.window', 'layout.border', '<see cref="Ext.data.Connection">Ext.data.Connection</see>']);
/// // Wildcards
/// <see cref="Ext.ExtContext.require">Ext.require</see>(['widget.*', 'layout.*', 'Ext.data.*']);
/// </code></pre>
/// <h3>Method 2: Explicitly exclude what you don't need:</h3>
/// <pre><code>// Syntax: Note that it must be in this chaining format.
/// <see cref="Ext.ExtContext.exclude">Ext.exclude</see>({String/Array} expressions)
/// .require({String/Array} expressions);
/// // Include everything except Ext.data.*
/// <see cref="Ext.ExtContext.exclude">Ext.exclude</see>('Ext.data.*').require('*');
/// // Include all widgets except widget.checkbox*,
/// // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
/// <see cref="Ext.ExtContext.exclude">Ext.exclude</see>('widget.checkbox*').require('widget.*');
/// </code></pre>
/// <h1>Synchronous Loading on Demand</h1>
/// <ul>
/// <li><p>Advantages:</p>
/// <ul>
/// <li>There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js
/// before</li>
/// </ul>
/// </li>
/// <li><p>Disadvantages:</p>
/// <ul>
/// <li>Not as good debugging experience since file name won't be shown (except in Firebug at the moment)</li>
/// <li>Must be from the same domain due to XHR restriction</li>
/// <li>Need a web server, same reason as above</li>
/// </ul>
/// </li>
/// </ul>
/// <p>There's one simple rule to follow: Instantiate everything with <see cref="Ext.ExtContext.create">Ext.create</see> instead of the <c>new</c> keyword</p>
/// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('widget.window', { ... }); // Instead of new <see cref="Ext.window.Window">Ext.window.Window</see>({...});
/// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.window.Window">Ext.window.Window</see>', {}); // Same as above, using full class name instead of alias
/// <see cref="Ext.ExtContext.widget">Ext.widget</see>('window', {}); // Same as above, all you need is the traditional `xtype`
/// </code></pre>
/// <p>Behind the scene, <see cref="Ext.ClassManager">Ext.ClassManager</see> will automatically check whether the given class name / alias has already
/// existed on the page. If it's not, <see cref="Ext.Loader">Ext.Loader</see> will immediately switch itself to synchronous mode and automatic load the given
/// class and all its dependencies.</p>
/// <h1>Hybrid Loading - The Best of Both Worlds</h1>
/// <p>It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:</p>
/// <h3>Step 1: Start writing your application using synchronous approach.</h3>
/// <p><see cref="Ext.Loader">Ext.Loader</see> will automatically fetch all dependencies on demand as they're needed during run-time. For example:</p>
/// <pre><code><see cref="Ext.ExtContext.onReady">Ext.onReady</see>(function(){
/// var window = <see cref="Ext.ExtContext.widget">Ext.widget</see>('window', {
/// width: 500,
/// height: 300,
/// layout: {
/// type: 'border',
/// padding: 5
/// },
/// title: 'Hello Dialog',
/// items: [{
/// title: 'Navigation',
/// collapsible: true,
/// region: 'west',
/// width: 200,
/// html: 'Hello',
/// split: true
/// }, {
/// title: 'TabPanel',
/// region: 'center'
/// }]
/// });
/// window.show();
/// })
/// </code></pre>
/// <h3>Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these:</h3>
/// <pre><code>[<see cref="Ext.Loader">Ext.Loader</see>] Synchronously loading '<see cref="Ext.window.Window">Ext.window.Window</see>'; consider adding <see cref="Ext.ExtContext.require">Ext.require</see>('<see cref="Ext.window.Window">Ext.window.Window</see>') before your application's code
/// ClassManager.js:432
/// [<see cref="Ext.Loader">Ext.Loader</see>] Synchronously loading '<see cref="Ext.layout.container.Border">Ext.layout.container.Border</see>'; consider adding <see cref="Ext.ExtContext.require">Ext.require</see>('<see cref="Ext.layout.container.Border">Ext.layout.container.Border</see>') before your application's code
/// </code></pre>
/// <p>Simply copy and paste the suggested code above <c><see cref="Ext.ExtContext.onReady">Ext.onReady</see></c>, i.e:</p>
/// <pre><code><see cref="Ext.ExtContext.require">Ext.require</see>('<see cref="Ext.window.Window">Ext.window.Window</see>');
/// <see cref="Ext.ExtContext.require">Ext.require</see>('<see cref="Ext.layout.container.Border">Ext.layout.container.Border</see>');
/// <see cref="Ext.ExtContext.onReady">Ext.onReady</see>(...);
/// </code></pre>
/// <p>Everything should now load via asynchronous mode.</p>
/// <h1>Deployment</h1>
/// <p>It's important to note that dynamic loading should only be used during development on your local machines.
/// During production, all dependencies should be combined into one single JavaScript file. <see cref="Ext.Loader">Ext.Loader</see> makes
/// the whole process of transitioning from / to between development / maintenance and production as easy as
/// possible. Internally <see cref="Ext.Loader.history">Ext.Loader.history</see> maintains the list of all dependencies your application
/// needs in the exact loading sequence. It's as simple as concatenating all files in this array into one,
/// then include it on top of your application.</p>
/// <p>This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.</p>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Loader
{
/// <summary>
/// Appends current timestamp to script files to prevent caching.
/// Defaults to: <c>true</c>
/// </summary>
public static bool disableCaching;
/// <summary>
/// The get parameter name for the cache buster's timestamp.
/// Defaults to: <c>"_dc"</c>
/// </summary>
public static JsString disableCachingParam;
/// <summary>
/// Whether or not to enable the dynamic dependency loading feature.
/// Defaults to: <c>false</c>
/// </summary>
public static bool enabled;
/// <summary>
/// True to prepare an asynchronous script tag for garbage collection (effective only
/// if preserveScripts is false)
/// Defaults to: <c>false</c>
/// </summary>
public static bool garbageCollect;
/// <summary>
/// The mapping from namespaces to file paths
/// <code>{
/// 'Ext': '.', // This is set by default, <see cref="Ext.layout.container.Container">Ext.layout.container.Container</see> will be
/// // loaded from ./layout/Container.js
/// 'My': './src/my_own_folder' // My.layout.Container will be loaded from
/// // ./src/my_own_folder/layout/Container.js
/// }
/// </code>
/// Note that all relative paths are relative to the current HTML document.
/// If not being specified, for example, <c>Other.awesome.Class</c>
/// will simply be loaded from <c>./Other/awesome/Class.js</c>
/// Defaults to: <c>{"Ext": "."}</c>
/// </summary>
public static JsObject paths;
/// <summary>
/// False to remove and optionally garbage-collect asynchronously loaded scripts,
/// True to retain script element for browser debugger compatibility and improved load performance.
/// Defaults to: <c>true</c>
/// </summary>
public static bool preserveScripts;
/// <summary>
/// millisecond delay between asynchronous script injection (prevents stack overflow on some user agents)
/// 'false' disables delay but potentially increases stack load.
/// Defaults to: <c>false</c>
/// </summary>
public static bool scriptChainDelay;
/// <summary>
/// Optional charset to specify encoding of dynamic script content.
/// </summary>
public static JsString scriptCharset;
/// <summary>
/// </summary>
private static JsObject classNameToFilePathMap{get;set;}
/// <summary>
/// Configuration
/// </summary>
private static JsObject config{get;set;}
/// <summary>
/// </summary>
private static JsObject documentHead{get;set;}
/// <summary>
/// Defaults to: <c>false</c>
/// </summary>
private static bool hasFileLoadError{get;set;}
/// <summary>
/// An array of class names to keep track of the dependency loading order.
/// This is not guaranteed to be the same everytime due to the asynchronous
/// nature of the Loader.
/// </summary>
public static JsArray history{get;set;}
/// <summary>
/// Maintain the list of files that have already been handled so that they never get double-loaded
/// </summary>
private static JsObject isClassFileLoaded{get;set;}
/// <summary>
/// </summary>
private static JsObject isFileLoaded{get;set;}
/// <summary>
/// </summary>
private static JsObject isInHistory{get;set;}
/// <summary>
/// Flag indicating whether there are still files being loaded
/// Defaults to: <c>false</c>
/// </summary>
private static bool isLoading{get;set;}
/// <summary>
/// Defaults to: <c>0</c>
/// </summary>
private static JsNumber numLoadedFiles{get;set;}
/// <summary>
/// Defaults to: <c>0</c>
/// </summary>
private static JsNumber numPendingFiles{get;set;}
/// <summary>
/// Contains classes referenced in uses properties.
/// </summary>
private static JsObject optionalRequires{get;set;}
/// <summary>
/// Maintain the queue for all dependencies. Each item in the array is an object of the format:
/// <code>{
/// requires: [...], // The required classes for this queue item
/// callback: function() { ... } // The function to execute when all classes specified in requires exist
/// }
/// </code>
/// </summary>
private static JsObject queue{get;set;}
/// <summary>
/// Maintain the list of listeners to execute when all required scripts are fully loaded
/// </summary>
private static JsObject readyListeners{get;set;}
/// <summary>
/// Map of fully qualified class names to an array of dependent classes.
/// </summary>
private static JsObject requiresMap{get;set;}
/// <summary>
/// The number of scripts loading via loadScript.
/// Defaults to: <c>0</c>
/// </summary>
private static JsNumber scriptsLoading{get;set;}
/// <summary>
/// Defaults to: <c>false</c>
/// </summary>
private static bool syncModeEnabled{get;set;}
/// <summary>
/// Ensure that any classes referenced in the uses property are loaded.
/// </summary>
/// <param name="classes">
/// </param>
private static void addUsedClasses(object classes){}
/// <summary>
/// Parameters<li><span>script</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>remove</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>collect</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="script">
/// </param>
/// <param name="remove">
/// </param>
/// <param name="collect">
/// </param>
private static void cleanupScriptElement(object script, object remove, object collect){}
/// <summary>
/// Turns on or off the "cache buster" applied to dynamically loaded scripts. Normally
/// dynamically loaded scripts have an extra query parameter appended to avoid stale
/// cached scripts. This method can be used to disable this mechanism, and is primarily
/// useful for testing. This is done using a cookie.
/// </summary>
/// <param name="disable"><p>True to disable the cache buster.</p>
/// </param>
/// <param name="path"><p>An optional path to scope the cookie.</p>
/// <p>Defaults to: <c>"/"</c></p></param>
private static void disableCacheBuster(bool disable, object path=null){}
/// <summary>
/// Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
/// Can be chained with more require and exclude methods, eg:
/// <code><see cref="Ext.ExtContext.exclude">Ext.exclude</see>('Ext.data.*').require('*');
/// <see cref="Ext.ExtContext.exclude">Ext.exclude</see>('widget.button*').require('widget.*');
/// </code>
/// </summary>
/// <param name="excludes">
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>object contains <c>require</c> method for chaining</p>
/// </div>
/// </returns>
public static object exclude(JsArray excludes){return null;}
/// <summary>
/// Get the config value corresponding to the specified name. If no name is given, will return the config object
/// </summary>
/// <param name="name"><p>The config property name</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div>
/// </div>
/// </returns>
public static object getConfig(JsString name){return null;}
/// <summary>
/// Translates a className to a file path by adding the
/// the proper prefix and converting the .'s to /'s. For example:
/// <code><see cref="Ext.Loader.setPath">Ext.Loader.setPath</see>('My', '/path/to/My');
/// alert(<see cref="Ext.Loader.getPath">Ext.Loader.getPath</see>('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
/// </code>
/// Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
/// <code><see cref="Ext.Loader.setPath">Ext.Loader.setPath</see>({
/// 'My': '/path/to/lib',
/// 'My.awesome': '/other/path/for/awesome/stuff',
/// 'My.awesome.more': '/more/awesome/path'
/// });
/// alert(<see cref="Ext.Loader.getPath">Ext.Loader.getPath</see>('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
/// alert(<see cref="Ext.Loader.getPath">Ext.Loader.getPath</see>('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
/// alert(<see cref="Ext.Loader.getPath">Ext.Loader.getPath</see>('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
/// alert(<see cref="Ext.Loader.getPath">Ext.Loader.getPath</see>('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
/// </code>
/// </summary>
/// <param name="className">
/// </param>
/// <returns>
/// <span><see cref="String">String</see></span><div><p>path</p>
/// </div>
/// </returns>
public static JsString getPath(JsString className){return null;}
/// <summary>
/// Parameters<li><span>className</span> : <see cref="String">String</see><div>
/// </div></li>
/// </summary>
/// <param name="className">
/// </param>
private static void getPrefix(JsString className){}
/// <summary>
/// Parameters<li><span>className</span> : <see cref="String">String</see><div>
/// </div></li>
/// </summary>
/// <param name="className">
/// </param>
private static void historyPush(JsString className){}
/// <summary>
/// Inject a script element to document's head, call onLoad and onError accordingly
/// </summary>
/// <param name="url">
/// </param>
/// <param name="onLoad">
/// </param>
/// <param name="onError">
/// </param>
/// <param name="scope">
/// </param>
/// <param name="charset">
/// </param>
private static void injectScriptElement(object url, object onLoad, object onError, object scope, object charset){}
/// <summary>
/// Parameters<li><span>className</span> : <see cref="String">String</see><div>
/// </div></li>
/// </summary>
/// <param name="className">
/// </param>
private static void isAClassNameWithAKnownPrefix(JsString className){}
/// <summary>
/// Loads the specified script URL and calls the supplied callbacks. If this method
/// is called before Ext.isReady, the script's load will delay the transition
/// to ready. This can be used to load arbitrary scripts that may contain further
/// Ext.require calls.
/// </summary>
/// <param name="options"><p>The options object or simply the URL to load.</p>
/// <ul><li><span>url</span> : <see cref="String">String</see><div><p>The URL from which to load the script.</p>
/// </div></li><li><span>onLoad</span> : <see cref="Function">Function</see> (optional)<div><p>The callback to call on successful load.</p>
/// </div></li><li><span>onError</span> : <see cref="Function">Function</see> (optional)<div><p>The callback to call on failure to load.</p>
/// </div></li><li><span>scope</span> : <see cref="Object">Object</see> (optional)<div><p>The scope (<c>this</c>) for the supplied callbacks.</p>
/// </div></li></ul></param>
public static void loadScript(object options=null){}
/// <summary>
/// Load a script file, supports both asynchronous and synchronous approaches
/// </summary>
/// <param name="url">
/// </param>
/// <param name="onLoad">
/// </param>
/// <param name="onError">
/// </param>
/// <param name="scope">
/// </param>
/// <param name="synchronous">
/// </param>
private static void loadScriptFile(object url, object onLoad, object onError, object scope, object synchronous){}
/// <summary>
/// Parameters<li><span>className</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>filePath</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>errorMessage</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>isSynchronous</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="className">
/// </param>
/// <param name="filePath">
/// </param>
/// <param name="errorMessage">
/// </param>
/// <param name="isSynchronous">
/// </param>
private static void onFileLoadError(object className, object filePath, object errorMessage, object isSynchronous){}
/// <summary>
/// Parameters<li><span>className</span> : <see cref="String">String</see><div>
/// </div></li><li><span>filePath</span> : <see cref="String">String</see><div>
/// </div></li>
/// </summary>
/// <param name="className">
/// </param>
/// <param name="filePath">
/// </param>
private static void onFileLoaded(JsString className, JsString filePath){}
/// <summary>
/// Add a new listener to be executed when all required scripts are fully loaded
/// </summary>
/// <param name="fn"><p>The function callback to be executed</p>
/// </param>
/// <param name="scope"><p>The execution scope (<c>this</c>) of the callback function</p>
/// </param>
/// <param name="withDomReady"><p>Whether or not to wait for document dom ready as well</p>
/// </param>
public static void onReady(System.Delegate fn, object scope, bool withDomReady){}
/// <summary>
/// Refresh all items in the queue. If all dependencies for an item exist during looping,
/// it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
/// empty
/// </summary>
private static void refreshQueue(){}
/// <summary>
/// Parameters<li><span>url</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="url">
/// </param>
private static void removeScriptElement(object url){}
/// <summary>
/// Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when
/// finishes, within the optional scope. This method is aliased by Ext.require for convenience
/// </summary>
/// <param name="expressions"><p>Can either be a string or an array of string</p>
/// </param>
/// <param name="fn"><p>The callback function</p>
/// </param>
/// <param name="scope"><p>The execution scope (<c>this</c>) of the callback function</p>
/// </param>
/// <param name="excludes"><p>Classes to be excluded, useful when being used with expressions</p>
/// </param>
public static void require(object expressions, System.Delegate fn=null, object scope=null, object excludes=null){}
/// <summary>
/// Set the configuration for the loader. This should be called right after ext-(debug).js
/// is included in the page, and before Ext.onReady. i.e:
/// <code><script type="text/javascript" src="ext-core-debug.js"></script>
/// <script type="text/javascript">
/// <see cref="Ext.Loader.setConfig">Ext.Loader.setConfig</see>({
/// enabled: true,
/// paths: {
/// 'My': 'my_own_path'
/// }
/// });
/// </script>
/// <script type="text/javascript">
/// <see cref="Ext.ExtContext.require">Ext.require</see>(...);
/// <see cref="Ext.ExtContext.onReady">Ext.onReady</see>(function() {
/// // application code here
/// });
/// </script>
/// </code>
/// Refer to config options of <see cref="Ext.Loader">Ext.Loader</see> for the list of possible properties
/// </summary>
/// <param name="config"><p>The config object to override the default values</p>
/// </param>
/// <returns>
/// <span><see cref="Ext.Loader">Ext.Loader</see></span><div><p>this</p>
/// </div>
/// </returns>
public static Loader setConfig(object config){return null;}
/// <summary>
/// Sets the path of a namespace.
/// For Example:
/// <code><see cref="Ext.Loader.setPath">Ext.Loader.setPath</see>('Ext', '.');
/// </code>
/// </summary>
/// <param name="name"><p>See <see cref="Ext.Function.flexSetter">flexSetter</see></p>
/// </param>
/// <param name="path"><p>See <see cref="Ext.Function.flexSetter">flexSetter</see></p>
/// </param>
/// <returns>
/// <span><see cref="Ext.Loader">Ext.Loader</see></span><div><p>this</p>
/// </div>
/// </returns>
public static Loader setPath(object name, JsString path){return null;}
/// <summary>
/// Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by Ext.syncRequire for convenience
/// </summary>
/// <param name="expressions"><p>Can either be a string or an array of string</p>
/// </param>
/// <param name="fn"><p>The callback function</p>
/// </param>
/// <param name="scope"><p>The execution scope (<c>this</c>) of the callback function</p>
/// </param>
/// <param name="excludes"><p>Classes to be excluded, useful when being used with expressions</p>
/// </param>
public static void syncRequire(object expressions, System.Delegate fn=null, object scope=null, object excludes=null){}
/// <summary>
/// </summary>
private static void triggerReady(){}
public Loader(LoaderConfig config){}
public Loader(){}
public Loader(params object[] args){}
}
#endregion
#region LoaderConfig
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class LoaderConfig
{
/// <summary>
/// Appends current timestamp to script files to prevent caching.
/// Defaults to: <c>true</c>
/// </summary>
public bool disableCaching;
/// <summary>
/// The get parameter name for the cache buster's timestamp.
/// Defaults to: <c>"_dc"</c>
/// </summary>
public JsString disableCachingParam;
/// <summary>
/// Whether or not to enable the dynamic dependency loading feature.
/// Defaults to: <c>false</c>
/// </summary>
public bool enabled;
/// <summary>
/// True to prepare an asynchronous script tag for garbage collection (effective only
/// if preserveScripts is false)
/// Defaults to: <c>false</c>
/// </summary>
public bool garbageCollect;
/// <summary>
/// The mapping from namespaces to file paths
/// <code>{
/// 'Ext': '.', // This is set by default, <see cref="Ext.layout.container.Container">Ext.layout.container.Container</see> will be
/// // loaded from ./layout/Container.js
/// 'My': './src/my_own_folder' // My.layout.Container will be loaded from
/// // ./src/my_own_folder/layout/Container.js
/// }
/// </code>
/// Note that all relative paths are relative to the current HTML document.
/// If not being specified, for example, <c>Other.awesome.Class</c>
/// will simply be loaded from <c>./Other/awesome/Class.js</c>
/// Defaults to: <c>{"Ext": "."}</c>
/// </summary>
public JsObject paths;
/// <summary>
/// False to remove and optionally garbage-collect asynchronously loaded scripts,
/// True to retain script element for browser debugger compatibility and improved load performance.
/// Defaults to: <c>true</c>
/// </summary>
public bool preserveScripts;
/// <summary>
/// millisecond delay between asynchronous script injection (prevents stack overflow on some user agents)
/// 'false' disables delay but potentially increases stack load.
/// Defaults to: <c>false</c>
/// </summary>
public bool scriptChainDelay;
/// <summary>
/// Optional charset to specify encoding of dynamic script content.
/// </summary>
public JsString scriptCharset;
public LoaderConfig(params object[] args){}
}
#endregion
#region LoaderEvents
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class LoaderEvents
{
public LoaderEvents(params object[] args){}
}
#endregion
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Scientia.HtmlRenderer.Core;
using Scientia.HtmlRenderer.Core.Entities;
using Scientia.HtmlRenderer.Core.Utils;
using Scientia.HtmlRenderer.WPF.Adapters;
using Scientia.HtmlRenderer.WPF.Utilities;
namespace Scientia.HtmlRenderer.WPF
{
/// <summary>
/// Standalone static class for simple and direct HTML rendering.<br/>
/// For WPF UI prefer using HTML controls: <see cref="HtmlPanel"/> or <see cref="HtmlLabel"/>.<br/>
/// For low-level control and performance consider using <see cref="HtmlContainer"/>.<br/>
/// </summary>
/// <remarks>
/// <para>
/// <b>Rendering to image</b><br/>
/// // TODO:a update!
/// See https://htmlrenderer.codeplex.com/wikipage?title=Image%20generation <br/>
/// Because of GDI text rendering issue with alpha channel clear type text rendering rendering to image requires special handling.<br/>
/// <u>Solid color background -</u> generate an image where the background is filled with solid color and all the html is rendered on top
/// of the background color, GDI text rendering will be used. (RenderToImage method where the first argument is html string)<br/>
/// <u>Image background -</u> render html on top of existing image with whatever currently exist but it cannot have transparent pixels,
/// GDI text rendering will be used. (RenderToImage method where the first argument is Image object)<br/>
/// <u>Transparent background -</u> render html to empty image using GDI+ text rendering, the generated image can be transparent.
/// </para>
/// <para>
/// <b>Overwrite stylesheet resolution</b><br/>
/// Exposed by optional "stylesheetLoad" delegate argument.<br/>
/// Invoked when a stylesheet is about to be loaded by file path or URL in 'link' element.<br/>
/// Allows to overwrite the loaded stylesheet by providing the stylesheet data manually, or different source (file or URL) to load from.<br/>
/// Example: The stylesheet 'href' can be non-valid URI string that is interpreted in the overwrite delegate by custom logic to pre-loaded stylesheet object<br/>
/// If no alternative data is provided the original source will be used.<br/>
/// </para>
/// <para>
/// <b>Overwrite image resolution</b><br/>
/// Exposed by optional "imageLoad" delegate argument.<br/>
/// Invoked when an image is about to be loaded by file path, URL or inline data in 'img' element or background-image CSS style.<br/>
/// Allows to overwrite the loaded image by providing the image object manually, or different source (file or URL) to load from.<br/>
/// Example: image 'src' can be non-valid string that is interpreted in the overwrite delegate by custom logic to resource image object<br/>
/// Example: image 'src' in the html is relative - the overwrite intercepts the load and provide full source URL to load the image from<br/>
/// Example: image download requires authentication - the overwrite intercepts the load, downloads the image to disk using custom code and provide
/// file path to load the image from.<br/>
/// If no alternative data is provided the original source will be used.<br/>
/// Note: Cannot use asynchronous scheme overwrite scheme.<br/>
/// </para>
/// </remarks>
/// <example>
/// <para>
/// <b>Simple rendering</b><br/>
/// HtmlRender.Render(g, "<![CDATA[<div>Hello <b>World</b></div>]]>");<br/>
/// HtmlRender.Render(g, "<![CDATA[<div>Hello <b>World</b></div>]]>", 10, 10, 500, CssData.Parse("body {font-size: 20px}")");<br/>
/// </para>
/// <para>
/// <b>Image rendering</b><br/>
/// HtmlRender.RenderToImage("<![CDATA[<div>Hello <b>World</b></div>]]>", new Size(600,400));<br/>
/// HtmlRender.RenderToImage("<![CDATA[<div>Hello <b>World</b></div>]]>", 600);<br/>
/// HtmlRender.RenderToImage(existingImage, "<![CDATA[<div>Hello <b>World</b></div>]]>");<br/>
/// </para>
/// </example>
public static class HtmlRender
{
/// <summary>
/// Adds a font family to be used in html rendering.<br/>
/// The added font will be used by all rendering function including <see cref="HtmlContainer"/> and all WPF controls.
/// </summary>
/// <remarks>
/// The given font family instance must be remain alive while the renderer is in use.<br/>
/// If loaded from file then the file must not be deleted.
/// </remarks>
/// <param name="fontFamily">The font family to add.</param>
public static void AddFontFamily(FontFamily fontFamily)
{
ArgChecker.AssertArgNotNull(fontFamily, "fontFamily");
WpfAdapter.Instance.AddFontFamily(new FontFamilyAdapter(fontFamily));
}
/// <summary>
/// Adds a font mapping from <paramref name="fromFamily"/> to <paramref name="toFamily"/> iff the <paramref name="fromFamily"/> is not found.<br/>
/// When the <paramref name="fromFamily"/> font is used in rendered html and is not found in existing
/// fonts (installed or added) it will be replaced by <paramref name="toFamily"/>.<br/>
/// </summary>
/// <remarks>
/// This fonts mapping can be used as a fallback in case the requested font is not installed in the client system.
/// </remarks>
/// <param name="fromFamily">the font family to replace</param>
/// <param name="toFamily">the font family to replace with</param>
public static void AddFontFamilyMapping(string fromFamily, string toFamily)
{
ArgChecker.AssertArgNotNullOrEmpty(fromFamily, "fromFamily");
ArgChecker.AssertArgNotNullOrEmpty(toFamily, "toFamily");
WpfAdapter.Instance.AddFontFamilyMapping(fromFamily, toFamily);
}
/// <summary>
/// Parse the given stylesheet to <see cref="CssData"/> object.<br/>
/// If <paramref name="combineWithDefault"/> is true the parsed css blocks are added to the
/// default css data (as defined by W3), merged if class name already exists. If false only the data in the given stylesheet is returned.
/// </summary>
/// <seealso cref="http://www.w3.org/TR/CSS21/sample.html"/>
/// <param name="stylesheet">the stylesheet source to parse</param>
/// <param name="combineWithDefault">true - combine the parsed css data with default css data, false - return only the parsed css data</param>
/// <returns>the parsed css data</returns>
public static CssData ParseStyleSheet(string stylesheet, bool combineWithDefault = true)
{
return CssData.Parse(WpfAdapter.Instance, stylesheet, combineWithDefault);
}
/// <summary>
/// Measure the size (width and height) required to draw the given html under given max width restriction.<br/>
/// If no max width restriction is given the layout will use the maximum possible width required by the content,
/// it can be the longest text line or full image width.<br/>
/// </summary>
/// <param name="html">HTML source to render</param>
/// <param name="maxWidth">optional: bound the width of the html to render in (default - 0, unlimited)</param>
/// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
/// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
/// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
/// <returns>the size required for the html</returns>
public static Size Measure(string html, double maxWidth = 0, CssData cssData = null, EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler<HtmlImageLoadEventArgs> imageLoad = null)
{
Size actualSize = Size.Empty;
if (!string.IsNullOrEmpty(html))
{
using (var container = new HtmlContainer())
{
container.MaxSize = new Size(maxWidth, 0);
container.AvoidAsyncImagesLoading = true;
container.AvoidImagesLateLoading = true;
if (stylesheetLoad != null)
{
container.StylesheetLoad += stylesheetLoad;
}
if (imageLoad != null)
{
container.ImageLoad += imageLoad;
}
container.SetHtml(html, cssData);
container.PerformLayout();
actualSize = container.ActualSize;
}
}
return actualSize;
}
/// <summary>
/// Renders the specified HTML source on the specified location and max width restriction.<br/>
/// If <paramref name="maxWidth"/> is zero the html will use all the required width, otherwise it will perform line
/// wrap as specified in the html<br/>
/// Returned is the actual width and height of the rendered html.<br/>
/// </summary>
/// <param name="g">Device to render with</param>
/// <param name="html">HTML source to render</param>
/// <param name="left">optional: the left most location to start render the html at (default - 0)</param>
/// <param name="top">optional: the top most location to start render the html at (default - 0)</param>
/// <param name="maxWidth">optional: bound the width of the html to render in (default - 0, unlimited)</param>
/// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
/// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
/// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
/// <returns>the actual size of the rendered html</returns>
public static Size Render(DrawingContext g, string html, double left = 0, double top = 0, double maxWidth = 0, CssData cssData = null, EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler<HtmlImageLoadEventArgs> imageLoad = null)
{
ArgChecker.AssertArgNotNull(g, "g");
return RenderClip(g, html, new Point(left, top), new Size(maxWidth, 0), cssData, stylesheetLoad, imageLoad);
}
/// <summary>
/// Renders the specified HTML source on the specified location and max size restriction.<br/>
/// If <paramref name="maxSize"/>.Width is zero the html will use all the required width, otherwise it will perform line
/// wrap as specified in the html<br/>
/// If <paramref name="maxSize"/>.Height is zero the html will use all the required height, otherwise it will clip at the
/// given max height not rendering the html below it.<br/>
/// Returned is the actual width and height of the rendered html.<br/>
/// </summary>
/// <param name="g">Device to render with</param>
/// <param name="html">HTML source to render</param>
/// <param name="location">the top-left most location to start render the html at</param>
/// <param name="maxSize">the max size of the rendered html (if height above zero it will be clipped)</param>
/// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
/// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
/// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
/// <returns>the actual size of the rendered html</returns>
public static Size Render(DrawingContext g, string html, Point location, Size maxSize, CssData cssData = null, EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler<HtmlImageLoadEventArgs> imageLoad = null)
{
ArgChecker.AssertArgNotNull(g, "g");
return RenderClip(g, html, location, maxSize, cssData, stylesheetLoad, imageLoad);
}
/// <summary>
/// Renders the specified HTML into a new image of the requested size.<br/>
/// The HTML will be layout by the given size but will be clipped if cannot fit.<br/>
/// </summary>
/// <param name="html">HTML source to render</param>
/// <param name="size">The size of the image to render into, layout html by width and clipped by height</param>
/// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
/// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
/// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
/// <returns>the generated image of the html</returns>
public static BitmapFrame RenderToImage(
string html,
Size size,
CssData cssData = null,
EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad = null,
EventHandler<HtmlImageLoadEventArgs> imageLoad = null)
{
var renderTarget = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);
if (!string.IsNullOrEmpty(html))
{
// render HTML into the visual
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext g = drawingVisual.RenderOpen())
{
RenderHtml(g, html, new Point(), size, cssData, stylesheetLoad, imageLoad);
}
// render visual into target bitmap
renderTarget.Render(drawingVisual);
}
return BitmapFrame.Create(renderTarget);
}
/// <summary>
/// Renders the specified HTML into a new image of unknown size that will be determined by max width/height and HTML layout.<br/>
/// If <paramref name="maxWidth"/> is zero the html will use all the required width, otherwise it will perform line
/// wrap as specified in the html<br/>
/// If <paramref name="maxHeight"/> is zero the html will use all the required height, otherwise it will clip at the
/// given max height not rendering the html below it.<br/>
/// <p>
/// Limitation: The image cannot have transparent background, by default it will be white.<br/>
/// See "Rendering to image" remarks section on <see cref="HtmlRender"/>.<br/>
/// </p>
/// </summary>
/// <param name="html">HTML source to render</param>
/// <param name="maxWidth">optional: the max width of the rendered html, if not zero and html cannot be layout within the limit it will be clipped</param>
/// <param name="maxHeight">optional: the max height of the rendered html, if not zero and html cannot be layout within the limit it will be clipped</param>
/// <param name="backgroundColor">optional: the color to fill the image with (default - white)</param>
/// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
/// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
/// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
/// <returns>the generated image of the html</returns>
public static BitmapFrame RenderToImage(
string html,
int maxWidth = 0,
int maxHeight = 0,
Color backgroundColor = new Color(),
CssData cssData = null,
EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad = null,
EventHandler<HtmlImageLoadEventArgs> imageLoad = null)
{
return RenderToImage(html, Size.Empty, new Size(maxWidth, maxHeight), backgroundColor, cssData, stylesheetLoad, imageLoad);
}
/// <summary>
/// Renders the specified HTML into a new image of unknown size that will be determined by min/max width/height and HTML layout.<br/>
/// If <paramref name="maxSize.Width"/> is zero the html will use all the required width, otherwise it will perform line
/// wrap as specified in the html<br/>
/// If <paramref name="maxSize.Height"/> is zero the html will use all the required height, otherwise it will clip at the
/// given max height not rendering the html below it.<br/>
/// If <paramref name="minSize"/> (Width/Height) is above zero the rendered image will not be smaller than the given min size.<br/>
/// <p>
/// Limitation: The image cannot have transparent background, by default it will be white.<br/>
/// See "Rendering to image" remarks section on <see cref="HtmlRender"/>.<br/>
/// </p>
/// </summary>
/// <param name="html">HTML source to render</param>
/// <param name="minSize">optional: the min size of the rendered html (zero - not limit the width/height)</param>
/// <param name="maxSize">optional: the max size of the rendered html, if not zero and html cannot be layout within the limit it will be clipped (zero - not limit the width/height)</param>
/// <param name="backgroundColor">optional: the color to fill the image with (default - white)</param>
/// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
/// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
/// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
/// <returns>the generated image of the html</returns>
public static BitmapFrame RenderToImage(
string html,
Size minSize,
Size maxSize,
Color backgroundColor = new Color(),
CssData cssData = null,
EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad = null,
EventHandler<HtmlImageLoadEventArgs> imageLoad = null)
{
RenderTargetBitmap renderTarget;
if (!string.IsNullOrEmpty(html))
{
using (var container = new HtmlContainer())
{
container.AvoidAsyncImagesLoading = true;
container.AvoidImagesLateLoading = true;
if (stylesheetLoad != null)
{
container.StylesheetLoad += stylesheetLoad;
}
if (imageLoad != null)
{
container.ImageLoad += imageLoad;
}
container.SetHtml(html, cssData);
var finalSize = MeasureHtmlByRestrictions(container, minSize, maxSize);
container.MaxSize = finalSize;
renderTarget = new RenderTargetBitmap((int)finalSize.Width, (int)finalSize.Height, 96, 96, PixelFormats.Pbgra32);
// render HTML into the visual
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext g = drawingVisual.RenderOpen())
{
container.PerformPaint(g, new Rect(new Size(maxSize.Width > 0 ? maxSize.Width : double.MaxValue, maxSize.Height > 0 ? maxSize.Height : double.MaxValue)));
}
// render visual into target bitmap
renderTarget.Render(drawingVisual);
}
}
else
{
renderTarget = new RenderTargetBitmap(0, 0, 96, 96, PixelFormats.Pbgra32);
}
return BitmapFrame.Create(renderTarget);
}
#region Private methods
/// <summary>
/// Measure the size of the html by performing layout under the given restrictions.
/// </summary>
/// <param name="htmlContainer">the html to calculate the layout for</param>
/// <param name="minSize">the minimal size of the rendered html (zero - not limit the width/height)</param>
/// <param name="maxSize">the maximum size of the rendered html, if not zero and html cannot be layout within the limit it will be clipped (zero - not limit the width/height)</param>
/// <returns>return: the size of the html to be rendered within the min/max limits</returns>
private static Size MeasureHtmlByRestrictions(HtmlContainer htmlContainer, Size minSize, Size maxSize)
{
// use desktop created graphics to measure the HTML
using (var mg = new GraphicsAdapter())
{
var sizeInt = HtmlRendererUtils.MeasureHtmlByRestrictions(mg, htmlContainer.HtmlContainerInt, Utils.Convert(minSize), Utils.Convert(maxSize));
if (maxSize.Width < 1 && sizeInt.Width > 4096)
{
sizeInt.Width = 4096;
}
return Utils.ConvertRound(sizeInt);
}
}
/// <summary>
/// Renders the specified HTML source on the specified location and max size restriction.<br/>
/// If <paramref name="maxSize"/>.Width is zero the html will use all the required width, otherwise it will perform line
/// wrap as specified in the html<br/>
/// If <paramref name="maxSize"/>.Height is zero the html will use all the required height, otherwise it will clip at the
/// given max height not rendering the html below it.<br/>
/// Clip the graphics so the html will not be rendered outside the max height bound given.<br/>
/// Returned is the actual width and height of the rendered html.<br/>
/// </summary>
/// <param name="g">Device to render with</param>
/// <param name="html">HTML source to render</param>
/// <param name="location">the top-left most location to start render the html at</param>
/// <param name="maxSize">the max size of the rendered html (if height above zero it will be clipped)</param>
/// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
/// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
/// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
/// <returns>the actual size of the rendered html</returns>
private static Size RenderClip(DrawingContext g, string html, Point location, Size maxSize, CssData cssData, EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad, EventHandler<HtmlImageLoadEventArgs> imageLoad)
{
if (maxSize.Height > 0)
{
g.PushClip(new RectangleGeometry(new Rect(location, maxSize)));
}
var actualSize = RenderHtml(g, html, location, maxSize, cssData, stylesheetLoad, imageLoad);
if (maxSize.Height > 0)
{
g.Pop();
}
return actualSize;
}
/// <summary>
/// Renders the specified HTML source on the specified location and max size restriction.<br/>
/// If <paramref name="maxSize"/>.Width is zero the html will use all the required width, otherwise it will perform line
/// wrap as specified in the html<br/>
/// If <paramref name="maxSize"/>.Height is zero the html will use all the required height, otherwise it will clip at the
/// given max height not rendering the html below it.<br/>
/// Returned is the actual width and height of the rendered html.<br/>
/// </summary>
/// <param name="g">Device to render with</param>
/// <param name="html">HTML source to render</param>
/// <param name="location">the top-left most location to start render the html at</param>
/// <param name="maxSize">the max size of the rendered html (if height above zero it will be clipped)</param>
/// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
/// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
/// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
/// <returns>the actual size of the rendered html</returns>
private static Size RenderHtml(DrawingContext g, string html, Point location, Size maxSize, CssData cssData, EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad, EventHandler<HtmlImageLoadEventArgs> imageLoad)
{
Size actualSize = Size.Empty;
if (!string.IsNullOrEmpty(html))
{
using (var container = new HtmlContainer())
{
container.Location = location;
container.MaxSize = maxSize;
container.AvoidAsyncImagesLoading = true;
container.AvoidImagesLateLoading = true;
if (stylesheetLoad != null)
{
container.StylesheetLoad += stylesheetLoad;
}
if (imageLoad != null)
{
container.ImageLoad += imageLoad;
}
container.SetHtml(html, cssData);
container.PerformLayout();
container.PerformPaint(g, new Rect(0, 0, double.MaxValue, double.MaxValue));
actualSize = container.ActualSize;
}
}
return actualSize;
}
#endregion
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: 576082 $
* $Date: 2007-09-16 14:04:01 +0200 (dim., 16 sept. 2007) $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Xml;
using IBatisNet.Common;
using IBatisNet.Common.Utilities;
using IBatisNet.Common.Utilities.Objects;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper.DataExchange;
using IBatisNet.DataMapper.TypeHandlers;
namespace IBatisNet.DataMapper.Scope
{
/// <summary>
/// The ConfigurationScope maintains the state of the build process.
/// </summary>
public class ConfigurationScope : IScope
{
/// <summary>
/// Empty parameter map
/// </summary>
public const string EMPTY_PARAMETER_MAP = "iBATIS.Empty.ParameterMap";
#region Fields
private ErrorContext _errorContext = null;
private HybridDictionary _providers = new HybridDictionary();
private HybridDictionary _sqlIncludes = new HybridDictionary();
private NameValueCollection _properties = new NameValueCollection();
private XmlDocument _sqlMapConfigDocument = null;
private XmlDocument _sqlMapDocument = null;
private XmlNode _nodeContext = null;
private bool _useConfigFileWatcher = false;
private bool _useStatementNamespaces = false;
private bool _isCacheModelsEnabled = false;
private bool _useReflectionOptimizer = true;
private bool _validateSqlMap = false;
private bool _isCallFromDao = false;
private ISqlMapper _sqlMapper = null;
private string _sqlMapNamespace = null;
private DataSource _dataSource = null;
private bool _isXmlValid = true;
private XmlNamespaceManager _nsmgr = null;
private HybridDictionary _cacheModelFlushOnExecuteStatements = new HybridDictionary();
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public ConfigurationScope()
{
_errorContext = new ErrorContext();
_providers.Clear();
}
#endregion
#region Properties
/// <summary>
/// The list of sql fragment
/// </summary>
public HybridDictionary SqlIncludes
{
get { return _sqlIncludes; }
}
/// <summary>
/// XmlNamespaceManager
/// </summary>
public XmlNamespaceManager XmlNamespaceManager
{
set { _nsmgr = value; }
get { return _nsmgr; }
}
/// <summary>
/// Set if the parser should validate the sqlMap documents
/// </summary>
public bool ValidateSqlMap
{
set { _validateSqlMap = value; }
get { return _validateSqlMap; }
}
/// <summary>
/// Tells us if the xml configuration file validate the schema
/// </summary>
public bool IsXmlValid
{
set { _isXmlValid = value; }
get { return _isXmlValid; }
}
/// <summary>
/// The current SqlMap namespace.
/// </summary>
public string SqlMapNamespace
{
set { _sqlMapNamespace = value; }
get { return _sqlMapNamespace; }
}
/// <summary>
/// The SqlMapper we are building.
/// </summary>
public ISqlMapper SqlMapper
{
set { _sqlMapper = value; }
get { return _sqlMapper; }
}
/// <summary>
/// A factory for DataExchange objects
/// </summary>
public DataExchangeFactory DataExchangeFactory
{
get { return _sqlMapper.DataExchangeFactory; }
}
/// <summary>
/// Tell us if we are in a DataAccess context.
/// </summary>
public bool IsCallFromDao
{
set { _isCallFromDao = value; }
get { return _isCallFromDao; }
}
/// <summary>
/// Tell us if we cache model is enabled.
/// </summary>
public bool IsCacheModelsEnabled
{
set { _isCacheModelsEnabled = value; }
get { return _isCacheModelsEnabled; }
}
/// <summary>
/// External data source
/// </summary>
public DataSource DataSource
{
set { _dataSource = value; }
get { return _dataSource; }
}
/// <summary>
/// The current context node we are analizing
/// </summary>
public XmlNode NodeContext
{
set { _nodeContext = value; }
get { return _nodeContext; }
}
/// <summary>
/// The XML SqlMap config file
/// </summary>
public XmlDocument SqlMapConfigDocument
{
set { _sqlMapConfigDocument = value; }
get { return _sqlMapConfigDocument; }
}
/// <summary>
/// A XML SqlMap file
/// </summary>
public XmlDocument SqlMapDocument
{
set { _sqlMapDocument = value; }
get { return _sqlMapDocument; }
}
/// <summary>
/// Tell us if we use Configuration File Watcher
/// </summary>
public bool UseConfigFileWatcher
{
set { _useConfigFileWatcher = value; }
get { return _useConfigFileWatcher; }
}
/// <summary>
/// Tell us if we use statements namespaces
/// </summary>
public bool UseStatementNamespaces
{
set { _useStatementNamespaces = value; }
get { return _useStatementNamespaces; }
}
/// <summary>
/// Get the request's error context
/// </summary>
public ErrorContext ErrorContext
{
get { return _errorContext; }
}
/// <summary>
/// List of providers
/// </summary>
public HybridDictionary Providers
{
get { return _providers; }
}
/// <summary>
/// List of global properties
/// </summary>
public NameValueCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Indicates if we can use reflection optimizer.
/// </summary>
public bool UseReflectionOptimizer
{
get { return _useReflectionOptimizer; }
set { _useReflectionOptimizer = value; }
}
/// <summary>
/// Temporary storage for mapping cache model ids (key is System.String) to statements (value is IList which contains IMappedStatements).
/// </summary>
public HybridDictionary CacheModelFlushOnExecuteStatements
{
get { return _cacheModelFlushOnExecuteStatements; }
set { _cacheModelFlushOnExecuteStatements = value; }
}
#endregion
/// <summary>
/// Register under Statement Name or Fully Qualified Statement Name
/// </summary>
/// <param name="id">An Identity</param>
/// <returns>The new Identity</returns>
public string ApplyNamespace(string id)
{
string newId = id;
if (_sqlMapNamespace != null && _sqlMapNamespace.Length > 0
&& id != null && id.Length > 0 && id.IndexOf(".") < 0)
{
newId = _sqlMapNamespace + DomSqlMapBuilder.DOT + id;
}
return newId;
}
/// <summary>
/// Resolves the type handler.
/// </summary>
/// <param name="clazz">The clazz.</param>
/// <param name="memberName">Name of the member.</param>
/// <param name="clrType">Type of the CLR.</param>
/// <param name="dbType">Type of the db.</param>
/// <param name="forSetter">if set to <c>true</c> [for setter].</param>
/// <returns></returns>
public ITypeHandler ResolveTypeHandler(Type clazz, string memberName, string clrType, string dbType, bool forSetter)
{
ITypeHandler handler = null;
if (clazz == null)
{
handler = this.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
}
else if (typeof(IDictionary).IsAssignableFrom(clazz))
{
// IDictionary
if (clrType == null || clrType.Length == 0)
{
handler = this.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
}
else
{
try
{
Type type = TypeUtils.ResolveType(clrType);
handler = this.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, dbType);
}
catch (Exception e)
{
//#if dotnet2
throw new ConfigurationErrorsException("Error. Could not set TypeHandler. Cause: " + e.Message, e);
//#else
//throw new ConfigurationException("Error. Could not set TypeHandler. Cause: " + e.Message, e);
//#endif
}
}
}
else if (this.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(clazz, dbType) != null)
{
// Primitive
handler = this.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(clazz, dbType);
}
else
{
// .NET object
if (clrType == null || clrType.Length == 0)
{
Type type = null;
if (forSetter)
{
type = ObjectProbe.GetMemberTypeForSetter(clazz, memberName);
}
else
{
type = ObjectProbe.GetMemberTypeForGetter(clazz, memberName);
}
handler = this.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, dbType);
}
else
{
try
{
Type type = TypeUtils.ResolveType(clrType);
handler = this.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, dbType);
}
catch (Exception e)
{
//#if dotnet2
throw new ConfigurationErrorsException("Error. Could not set TypeHandler. Cause: " + e.Message, e);
//#else
//throw new ConfigurationException("Error. Could not set TypeHandler. Cause: " + e.Message, e);
//#endif
}
}
}
return handler;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
using System.Dynamic;
#endif
using System.Globalization;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private readonly List<object> _serializeStack = new List<object>();
private JsonSerializerProxy _internalSerializer;
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null);
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer.ContractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.UnderlyingType == typeof (byte[]))
{
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName);
writer.WriteValue(value);
writer.WriteEndObject();
return;
}
}
writer.WriteValue(value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter;
if ((((converter = (member != null) ? member.Converter : null) != null)
|| ((converter = (containerProperty != null) ? containerProperty.ItemConverter : null) != null)
|| ((converter = (containerContract != null) ? containerContract.ItemConverter : null) != null)
|| ((converter = valueContract.Converter) != null)
|| ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null)
|| ((converter = valueContract.InternalConverter) != null))
&& converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract) valueContract;
SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, containerContract, containerProperty);
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract) valueContract;
SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
break;
#endif
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
#endif
case JsonContractType.Linq:
((JToken) value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null && containerProperty != null)
isReference = containerProperty.ItemIsReference;
if (isReference == null && collectionContract != null)
isReference = collectionContract.ItemIsReference;
if (isReference == null)
isReference = contract.IsReference;
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
return false;
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
return false;
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.ReferenceResolver.IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return false;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.DefaultValue))
return false;
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return true;
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
referenceLoopHandling = property.ReferenceLoopHandling;
if (referenceLoopHandling == null && containerProperty != null)
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
if (referenceLoopHandling == null && containerContract != null)
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
if (_serializeStack.IndexOf(value) != -1)
{
switch (referenceLoopHandling.GetValueOrDefault(Serializer.ReferenceLoopHandling))
{
case ReferenceLoopHandling.Error:
string message = "Self referencing loop detected";
if (property != null)
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
return false;
case ReferenceLoopHandling.Serialize:
return true;
default:
throw new InvalidOperationException("Unexpected ReferenceLoopHandling value: '{0}'".FormatWith(CultureInfo.InvariantCulture, Serializer.ReferenceLoopHandling));
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
writer.WriteEndObject();
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !(PocketPC || NETFX_CORE || PORTABLE)
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
#if !SILVERLIGHT
&& !(converter is ComponentConverter)
#endif
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
#if !SILVERLIGHT
s = converter.ConvertToInvariantString(value);
#else
s = converter.ConvertToString(value);
#endif
return true;
}
}
#endif
#if SILVERLIGHT || PocketPC || NETFX_CORE
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
contract.InvokeOnSerialized(value, Serializer.Context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
contract.InvokeOnSerializing(value, Serializer.Context);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
foreach (JsonProperty property in contract.Properties)
{
try
{
if (!property.Ignored && property.Readable && ShouldSerialize(property, value) && IsSpecified(property, value))
{
if (property.PropertyContract == null)
property.PropertyContract = Serializer.ContractResolver.ResolveContract(property.PropertyType);
object memberValue = property.ValueProvider.GetValue(value);
JsonContract memberContract = (property.PropertyContract.UnderlyingType.IsSealed()) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
string propertyName = property.PropertyName;
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, memberValue);
continue;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
continue;
if (memberValue == null)
{
Required resolvedRequired = property._required ?? contract.ItemRequired ?? Required.Default;
if (resolvedRequired == Required.Always)
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
writer.WritePropertyName(propertyName);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
writer.WritePropertyName(JsonTypeReflector.TypePropertyName);
writer.WriteValue(ReflectionUtils.GetTypeName(type, Serializer.TypeNameAssemblyFormat, Serializer.Binder));
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
return;
_serializeStack.Add(value);
converter.WriteJson(writer, value, GetInternalSerializer());
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);
_serializeStack.Add(values.UnderlyingCollection);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingCollection, contract, index, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
}
private bool WriteStartArray(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
}
if (contract.ItemContract == null)
contract.ItemContract = Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof (object));
return writeMetadataObject;
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
#if !NET20
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")]
[SecuritySafeCritical]
#endif
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
contract.InvokeOnSerializing(value, Serializer.Context);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer.Context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null, member);
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
#endif
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
contract.InvokeOnSerializing(value, Serializer.Context);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (DynamicUtils.TryGetMember(value, memberName, out memberValue))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, GetContractSafe(memberValue), null, null, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
#endif
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer.TypeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
return true;
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
return true;
}
else if (containerContract != null && containerContract.ItemContract != null)
{
if (contract.UnderlyingType != containerContract.ItemContract.CreatedType)
return true;
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);
_serializeStack.Add(values.UnderlyingDictionary);
WriteObjectStart(writer, values.UnderlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
contract.ItemContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
int initialDepth = writer.Top;
// Mono Unity 3.0 fix
IWrappedDictionary d = values;
foreach (DictionaryEntry entry in d)
{
string propertyName = GetPropertyName(entry);
propertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
}
private string GetPropertyName(DictionaryEntry entry)
{
string propertyName;
if (ConvertUtils.IsConvertible(entry.Key))
return Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
else if (TryConvertToString(entry.Key, entry.Key.GetType(), out propertyName))
return propertyName;
else
return entry.Key.ToString();
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
return property.ShouldSerialize(target);
}
private bool IsSpecified(JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
return property.GetIsSpecified(target);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.IO
{
public partial class BinaryReader : System.IDisposable
{
public BinaryReader(System.IO.Stream input) { }
public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding) { }
public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding, bool leaveOpen) { }
public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected virtual void FillBuffer(int numBytes) { }
public virtual int PeekChar() { return default(int); }
public virtual int Read() { return default(int); }
public virtual int Read(byte[] buffer, int index, int count) { return default(int); }
public virtual int Read(char[] buffer, int index, int count) { return default(int); }
protected internal int Read7BitEncodedInt() { return default(int); }
public virtual bool ReadBoolean() { return default(bool); }
public virtual byte ReadByte() { return default(byte); }
public virtual byte[] ReadBytes(int count) { return default(byte[]); }
public virtual char ReadChar() { return default(char); }
public virtual char[] ReadChars(int count) { return default(char[]); }
public virtual decimal ReadDecimal() { return default(decimal); }
public virtual double ReadDouble() { return default(double); }
public virtual short ReadInt16() { return default(short); }
public virtual int ReadInt32() { return default(int); }
public virtual long ReadInt64() { return default(long); }
[System.CLSCompliantAttribute(false)]
public virtual sbyte ReadSByte() { return default(sbyte); }
public virtual float ReadSingle() { return default(float); }
public virtual string ReadString() { return default(string); }
[System.CLSCompliantAttribute(false)]
public virtual ushort ReadUInt16() { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public virtual uint ReadUInt32() { return default(uint); }
[System.CLSCompliantAttribute(false)]
public virtual ulong ReadUInt64() { return default(ulong); }
}
public partial class BinaryWriter : System.IDisposable
{
public static readonly System.IO.BinaryWriter Null;
protected System.IO.Stream OutStream;
protected BinaryWriter() { }
public BinaryWriter(System.IO.Stream output) { }
public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding) { }
public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding, bool leaveOpen) { }
public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual void Flush() { }
public virtual long Seek(int offset, System.IO.SeekOrigin origin) { return default(long); }
public virtual void Write(bool value) { }
public virtual void Write(byte value) { }
public virtual void Write(byte[] buffer) { }
public virtual void Write(byte[] buffer, int index, int count) { }
public virtual void Write(char ch) { }
public virtual void Write(char[] chars) { }
public virtual void Write(char[] chars, int index, int count) { }
public virtual void Write(decimal value) { }
public virtual void Write(double value) { }
public virtual void Write(short value) { }
public virtual void Write(int value) { }
public virtual void Write(long value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(sbyte value) { }
public virtual void Write(float value) { }
public virtual void Write(string value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(ushort value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(ulong value) { }
protected void Write7BitEncodedInt(int value) { }
}
public partial class EndOfStreamException : System.IO.IOException
{
public EndOfStreamException() { }
public EndOfStreamException(string message) { }
public EndOfStreamException(string message, System.Exception innerException) { }
}
public sealed partial class InvalidDataException : System.Exception
{
public InvalidDataException() { }
public InvalidDataException(string message) { }
public InvalidDataException(string message, System.Exception innerException) { }
}
public partial class MemoryStream : System.IO.Stream
{
public MemoryStream() { }
public MemoryStream(byte[] buffer) { }
public MemoryStream(byte[] buffer, bool writable) { }
public MemoryStream(byte[] buffer, int index, int count) { }
public MemoryStream(byte[] buffer, int index, int count, bool writable) { }
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { }
public MemoryStream(int capacity) { }
public override bool CanRead { get { return default(bool); } }
public override bool CanSeek { get { return default(bool); } }
public override bool CanWrite { get { return default(bool); } }
public virtual int Capacity { get { return default(int); } set { } }
public override long Length { get { return default(long); } }
public override long Position { get { return default(long); } set { } }
public override System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
protected override void Dispose(bool disposing) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public override int Read(byte[] buffer, int offset, int count) { buffer = default(byte[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); }
public override int ReadByte() { return default(int); }
public override long Seek(long offset, System.IO.SeekOrigin loc) { return default(long); }
public override void SetLength(long value) { }
public virtual byte[] ToArray() { return default(byte[]); }
public virtual bool TryGetBuffer(out System.ArraySegment<byte> buffer) { buffer = default(System.ArraySegment<byte>); return default(bool); }
public override void Write(byte[] buffer, int offset, int count) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public override void WriteByte(byte value) { }
public virtual void WriteTo(System.IO.Stream stream) { }
}
public enum SeekOrigin
{
Begin = 0,
Current = 1,
End = 2,
}
public abstract partial class Stream : System.IDisposable
{
public static readonly System.IO.Stream Null;
protected Stream() { }
public abstract bool CanRead { get; }
public abstract bool CanSeek { get; }
public virtual bool CanTimeout { get { return default(bool); } }
public abstract bool CanWrite { get; }
public abstract long Length { get; }
public abstract long Position { get; set; }
public virtual int ReadTimeout { get { return default(int); } set { } }
public virtual int WriteTimeout { get { return default(int); } set { } }
public void CopyTo(System.IO.Stream destination) { }
public void CopyTo(System.IO.Stream destination, int bufferSize) { }
public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination) { return default(System.Threading.Tasks.Task); }
public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, int bufferSize) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void Flush();
public System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public abstract int Read(byte[] buffer, int offset, int count);
public System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); }
public virtual int ReadByte() { return default(int); }
public abstract long Seek(long offset, System.IO.SeekOrigin origin);
public abstract void SetLength(long value);
public abstract void Write(byte[] buffer, int offset, int count);
public System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public virtual void WriteByte(byte value) { }
}
public partial class StreamReader : System.IO.TextReader
{
public static readonly new System.IO.StreamReader Null;
public StreamReader(System.IO.Stream stream) { }
public StreamReader(System.IO.Stream stream, bool detectEncodingFromByteOrderMarks) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) { }
public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } }
public virtual System.Text.Encoding CurrentEncoding { get { return default(System.Text.Encoding); } }
public bool EndOfStream { get { return default(bool); } }
public void DiscardBufferedData() { }
protected override void Dispose(bool disposing) { }
public override int Peek() { return default(int); }
public override int Read() { return default(int); }
public override int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public override int ReadBlock(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public override string ReadLine() { return default(string); }
public override System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); }
public override string ReadToEnd() { return default(string); }
public override System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); }
}
public partial class StreamWriter : System.IO.TextWriter
{
public static readonly new System.IO.StreamWriter Null;
public StreamWriter(System.IO.Stream stream) { }
public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding) { }
public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize) { }
public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize, bool leaveOpen) { }
public virtual bool AutoFlush { get { return default(bool); } set { } }
public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } }
public override System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } }
protected override void Dispose(bool disposing) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public override void Write(char value) { }
public override void Write(char[] buffer) { }
public override void Write(char[] buffer, int index, int count) { }
public override void Write(string value) { }
public override System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync() { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); }
}
public partial class StringReader : System.IO.TextReader
{
public StringReader(string s) { }
protected override void Dispose(bool disposing) { }
public override int Peek() { return default(int); }
public override int Read() { return default(int); }
public override int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public override System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public override string ReadLine() { return default(string); }
public override System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); }
public override string ReadToEnd() { return default(string); }
public override System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); }
}
public partial class StringWriter : System.IO.TextWriter
{
public StringWriter() { }
public StringWriter(System.IFormatProvider formatProvider) { }
public StringWriter(System.Text.StringBuilder sb) { }
public StringWriter(System.Text.StringBuilder sb, System.IFormatProvider formatProvider) { }
public override System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } }
protected override void Dispose(bool disposing) { }
public override System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Text.StringBuilder GetStringBuilder() { return default(System.Text.StringBuilder); }
public override string ToString() { return default(string); }
public override void Write(char value) { }
public override void Write(char[] buffer, int index, int count) { }
public override void Write(string value) { }
public override System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); }
}
public abstract partial class TextReader : System.IDisposable
{
public static readonly System.IO.TextReader Null;
protected TextReader() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual int Peek() { return default(int); }
public virtual int Read() { return default(int); }
public virtual int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual int ReadBlock(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual string ReadLine() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual string ReadToEnd() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); }
}
public abstract partial class TextWriter : System.IDisposable
{
protected char[] CoreNewLine;
public static readonly System.IO.TextWriter Null;
protected TextWriter() { }
protected TextWriter(System.IFormatProvider formatProvider) { }
public abstract System.Text.Encoding Encoding { get; }
public virtual System.IFormatProvider FormatProvider { get { return default(System.IFormatProvider); } }
public virtual string NewLine { get { return default(string); } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual void Flush() { }
public virtual System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public virtual void Write(bool value) { }
public abstract void Write(char value);
public virtual void Write(char[] buffer) { }
public virtual void Write(char[] buffer, int index, int count) { }
public virtual void Write(decimal value) { }
public virtual void Write(double value) { }
public virtual void Write(int value) { }
public virtual void Write(long value) { }
public virtual void Write(object value) { }
public virtual void Write(float value) { }
public virtual void Write(string value) { }
public virtual void Write(string format, object arg0) { }
public virtual void Write(string format, object arg0, object arg1) { }
public virtual void Write(string format, object arg0, object arg1, object arg2) { }
public virtual void Write(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(ulong value) { }
public virtual System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); }
public System.Threading.Tasks.Task WriteAsync(char[] buffer) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); }
public virtual void WriteLine() { }
public virtual void WriteLine(bool value) { }
public virtual void WriteLine(char value) { }
public virtual void WriteLine(char[] buffer) { }
public virtual void WriteLine(char[] buffer, int index, int count) { }
public virtual void WriteLine(decimal value) { }
public virtual void WriteLine(double value) { }
public virtual void WriteLine(int value) { }
public virtual void WriteLine(long value) { }
public virtual void WriteLine(object value) { }
public virtual void WriteLine(float value) { }
public virtual void WriteLine(string value) { }
public virtual void WriteLine(string format, object arg0) { }
public virtual void WriteLine(string format, object arg0, object arg1) { }
public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { }
public virtual void WriteLine(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public virtual void WriteLine(uint value) { }
[System.CLSCompliantAttribute(false)]
public virtual void WriteLine(ulong value) { }
public virtual System.Threading.Tasks.Task WriteLineAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); }
public System.Threading.Tasks.Task WriteLineAsync(char[] buffer) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); }
}
}
| |
using System;
using System.Collections.Generic;
using Content.Server.AI.Pathfinding.Accessible;
using Content.Server.AI.Pathfinding.Pathfinders;
using Content.Shared.Access.Systems;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
namespace Content.Server.AI.Pathfinding
{
public static class PathfindingHelpers
{
public static bool TryEndNode(ref PathfindingNode endNode, PathfindingArgs pathfindingArgs)
{
if (!Traversable(pathfindingArgs.CollisionMask, pathfindingArgs.Access, endNode))
{
if (pathfindingArgs.Proximity > 0.0f)
{
foreach (var node in BFSPathfinder.GetNodesInRange(pathfindingArgs, false))
{
endNode = node;
return true;
}
}
return false;
}
return true;
}
public static bool DirectionTraversable(int collisionMask, ICollection<string> access, PathfindingNode currentNode, Direction direction)
{
// If it's a diagonal we need to check NSEW to see if we can get to it and stop corner cutting, NE needs N and E etc.
// Given there's different collision layers stored for each node in the graph it's probably not worth it to cache this
// Also this will help with corner-cutting
PathfindingNode? northNeighbor = null;
PathfindingNode? southNeighbor = null;
PathfindingNode? eastNeighbor = null;
PathfindingNode? westNeighbor = null;
foreach (var neighbor in currentNode.GetNeighbors())
{
if (neighbor.TileRef.X == currentNode.TileRef.X &&
neighbor.TileRef.Y == currentNode.TileRef.Y + 1)
{
northNeighbor = neighbor;
continue;
}
if (neighbor.TileRef.X == currentNode.TileRef.X + 1 &&
neighbor.TileRef.Y == currentNode.TileRef.Y)
{
eastNeighbor = neighbor;
continue;
}
if (neighbor.TileRef.X == currentNode.TileRef.X &&
neighbor.TileRef.Y == currentNode.TileRef.Y - 1)
{
southNeighbor = neighbor;
continue;
}
if (neighbor.TileRef.X == currentNode.TileRef.X - 1 &&
neighbor.TileRef.Y == currentNode.TileRef.Y)
{
westNeighbor = neighbor;
continue;
}
}
switch (direction)
{
case Direction.NorthEast:
if (northNeighbor == null || eastNeighbor == null) return false;
if (!Traversable(collisionMask, access, northNeighbor) ||
!Traversable(collisionMask, access, eastNeighbor))
{
return false;
}
break;
case Direction.NorthWest:
if (northNeighbor == null || westNeighbor == null) return false;
if (!Traversable(collisionMask, access, northNeighbor) ||
!Traversable(collisionMask, access, westNeighbor))
{
return false;
}
break;
case Direction.SouthWest:
if (southNeighbor == null || westNeighbor == null) return false;
if (!Traversable(collisionMask, access, southNeighbor) ||
!Traversable(collisionMask, access, westNeighbor))
{
return false;
}
break;
case Direction.SouthEast:
if (southNeighbor == null || eastNeighbor == null) return false;
if (!Traversable(collisionMask, access, southNeighbor) ||
!Traversable(collisionMask, access, eastNeighbor))
{
return false;
}
break;
}
return true;
}
public static bool Traversable(int collisionMask, ICollection<string> access, PathfindingNode node)
{
if ((collisionMask & node.BlockedCollisionMask) != 0)
{
return false;
}
var accessSystem = EntitySystem.Get<AccessReaderSystem>();
foreach (var reader in node.AccessReaders)
{
if (!accessSystem.IsAllowed(reader, access))
{
return false;
}
}
return true;
}
public static Queue<TileRef> ReconstructPath(Dictionary<PathfindingNode, PathfindingNode> cameFrom, PathfindingNode current)
{
var running = new Stack<TileRef>();
running.Push(current.TileRef);
while (cameFrom.ContainsKey(current))
{
var previousCurrent = current;
current = cameFrom[current];
cameFrom.Remove(previousCurrent);
running.Push(current.TileRef);
}
var result = new Queue<TileRef>(running);
return result;
}
/// <summary>
/// This will reconstruct the path and fill in the tile holes as well
/// </summary>
/// <param name="cameFrom"></param>
/// <param name="current"></param>
/// <returns></returns>
public static Queue<TileRef> ReconstructJumpPath(Dictionary<PathfindingNode, PathfindingNode> cameFrom, PathfindingNode current)
{
var running = new Stack<TileRef>();
running.Push(current.TileRef);
while (cameFrom.ContainsKey(current))
{
var previousCurrent = current;
current = cameFrom[current];
var intermediate = previousCurrent;
cameFrom.Remove(previousCurrent);
var pathfindingSystem = IoCManager.Resolve<IEntitySystemManager>().GetEntitySystem<PathfindingSystem>();
var mapManager = IoCManager.Resolve<IMapManager>();
var grid = mapManager.GetGrid(current.TileRef.GridIndex);
// Get all the intermediate nodes
while (true)
{
var xOffset = 0;
var yOffset = 0;
if (intermediate.TileRef.X < current.TileRef.X)
{
xOffset += 1;
}
else if (intermediate.TileRef.X > current.TileRef.X)
{
xOffset -= 1;
}
else
{
xOffset = 0;
}
if (intermediate.TileRef.Y < current.TileRef.Y)
{
yOffset += 1;
}
else if (intermediate.TileRef.Y > current.TileRef.Y)
{
yOffset -= 1;
}
else
{
yOffset = 0;
}
intermediate = pathfindingSystem.GetNode(grid.GetTileRef(
new Vector2i(intermediate.TileRef.X + xOffset, intermediate.TileRef.Y + yOffset)));
if (intermediate.TileRef != current.TileRef)
{
// Hacky corner cut fix
running.Push(intermediate.TileRef);
continue;
}
break;
}
running.Push(current.TileRef);
}
var result = new Queue<TileRef>(running);
return result;
}
public static float OctileDistance(int dstX, int dstY)
{
if (dstX > dstY)
{
return 1.4f * dstY + (dstX - dstY);
}
return 1.4f * dstX + (dstY - dstX);
}
public static float OctileDistance(PathfindingNode endNode, PathfindingNode currentNode)
{
// "Fast Euclidean" / octile.
// This implementation is written down in a few sources; it just saves doing sqrt.
int dstX = Math.Abs(currentNode.TileRef.X - endNode.TileRef.X);
int dstY = Math.Abs(currentNode.TileRef.Y - endNode.TileRef.Y);
if (dstX > dstY)
{
return 1.4f * dstY + (dstX - dstY);
}
return 1.4f * dstX + (dstY - dstX);
}
public static float OctileDistance(TileRef endTile, TileRef startTile)
{
// "Fast Euclidean" / octile.
// This implementation is written down in a few sources; it just saves doing sqrt.
int dstX = Math.Abs(startTile.X - endTile.X);
int dstY = Math.Abs(startTile.Y - endTile.Y);
if (dstX > dstY)
{
return 1.4f * dstY + (dstX - dstY);
}
return 1.4f * dstX + (dstY - dstX);
}
public static float ManhattanDistance(PathfindingNode endNode, PathfindingNode currentNode)
{
return Math.Abs(currentNode.TileRef.X - endNode.TileRef.X) + Math.Abs(currentNode.TileRef.Y - endNode.TileRef.Y);
}
public static float? GetTileCost(PathfindingArgs pathfindingArgs, PathfindingNode start, PathfindingNode end)
{
if (!pathfindingArgs.NoClip && !Traversable(pathfindingArgs.CollisionMask, pathfindingArgs.Access, end))
{
return null;
}
if (!pathfindingArgs.AllowSpace && end.TileRef.Tile.IsEmpty)
{
return null;
}
var cost = 1.0f;
switch (pathfindingArgs.AllowDiagonals)
{
case true:
cost *= OctileDistance(end, start);
break;
// Manhattan distance
case false:
cost *= ManhattanDistance(end, start);
break;
}
return cost;
}
public static Direction RelativeDirection(PathfindingChunk endChunk, PathfindingChunk startChunk)
{
var xDiff = (endChunk.Indices.X - startChunk.Indices.X) / PathfindingChunk.ChunkSize;
var yDiff = (endChunk.Indices.Y - startChunk.Indices.Y) / PathfindingChunk.ChunkSize;
return RelativeDirection(xDiff, yDiff);
}
public static Direction RelativeDirection(PathfindingNode endNode, PathfindingNode startNode)
{
var xDiff = endNode.TileRef.X - startNode.TileRef.X;
var yDiff = endNode.TileRef.Y - startNode.TileRef.Y;
return RelativeDirection(xDiff, yDiff);
}
public static Direction RelativeDirection(int x, int y)
{
switch (x)
{
case -1:
switch (y)
{
case -1:
return Direction.SouthWest;
case 0:
return Direction.West;
case 1:
return Direction.NorthWest;
default:
throw new InvalidOperationException();
}
case 0:
switch (y)
{
case -1:
return Direction.South;
case 0:
throw new InvalidOperationException();
case 1:
return Direction.North;
default:
throw new InvalidOperationException();
}
case 1:
switch (y)
{
case -1:
return Direction.SouthEast;
case 0:
return Direction.East;
case 1:
return Direction.NorthEast;
default:
throw new InvalidOperationException();
}
default:
throw new InvalidOperationException();
}
}
}
}
| |
using System;
using System.Collections;
using xmljr.math;
namespace Pantry.Algorithms.ConvexHull2D
{
// ------------------------------------------------------------
// This implementation correctly handles duplicate PointDs, and
// multiple PointDs with the same x-coordinate.
// 1. Sort the PointDs lexicographically by increasing (x,y), thus
// finding also a leftmost PointD L and a rightmost PointD R.
// 2. Partition the PointD set into two lists, upper and lower, according as
// PointD is above or below the segment LR. The upper list begins with
// L and ends with R; the lower list begins with R and ends with L.
// 3. Traverse the PointD lists clockwise, eliminating all but the extreme
// PointDs (thus eliminating also duplicate PointDs).
// 4. Eliminate L from lower and R from upper, if necessary.
// 5. Join the PointD lists (in clockwise order) in an array.
class Convexhulltools
{
static public PointD [] GetProjectedPointArray(ArrayList L)
{
PointD [] Arr = new PointD[L.Count];
int writ = 0;
foreach(Vector4 V in L)
{
Arr[writ] = new PointD(V.x, V.z);
writ++;
}
return Arr;
}
static public ArrayList GetGuessListOfProjectedPointArray(PointD [] Arr, double y)
{
ArrayList L = new ArrayList();
foreach(PointD P in Arr)
L.Add(new Vector4(P.X,y,P.Y,0));
return L;
}
}
class Convexhull
{
public static ArrayList convexhull(ArrayList PointsV4)
{
double SumY = 0;
foreach(Vector4 V in PointsV4) SumY += V.y;
SumY /= PointsV4.Count;
PointD[] D = Convexhulltools.GetProjectedPointArray(PointsV4);
D = convexhull(D);
return Convexhulltools.GetGuessListOfProjectedPointArray(D, SumY);
}
public static PointD[] convexhull(PointD[] pts)
{
// Sort PointDs lexicographically by increasing (x, y)
int N = pts.Length;
if (N<=1)
return pts;
Polysort.Quicksort(pts);
PointD left = pts[0];
PointD right = pts[N-1];
// Partition into lower hull and upper hull
CDLL lower = new CDLL(left), upper = new CDLL(left);
for (int i=0; i<N; i++)
{
double det = PointD.Area2(left, right, pts[i]);
if (det > 0)
upper = upper.Append(new CDLL(pts[i]));
else if (det < 0)
lower = lower.Prepend(new CDLL(pts[i]));
}
lower = lower.Prepend(new CDLL(right));
upper = upper.Append(new CDLL(right)).Next;
// Eliminate PointDs not on the hull
eliminate(lower);
eliminate(upper);
// Eliminate duplicate endPointDs
if (lower.Prev.val.Equals(upper.val))
lower.Prev.Delete();
if (upper.Prev.val.Equals(lower.val))
upper.Prev.Delete();
// Join the lower and upper hull
PointD[] res = new PointD[lower.Size() + upper.Size()];
lower.CopyInto(res, 0);
upper.CopyInto(res, lower.Size());
return res;
}
// Graham's scan
private static void eliminate(CDLL start)
{
CDLL v = start, w = start.Prev;
bool fwd = false;
while (v.Next != start || !fwd)
{
if (v.Next == w)
fwd = true;
if (PointD.Area2(v.val, v.Next.val, v.Next.Next.val) < 0) // right turn
v = v.Next;
else
{ // left turn or straight
v.Next.Delete();
v = v.Prev;
}
}
}
}
// ------------------------------------------------------------
// PointDs in the plane
public class PointD : Ordered
{
private static readonly Random rnd = new Random();
private double x, y;
public int X
{
get
{
return (int)x;
}
set
{
x=(double)value;
}
}
public int Y
{
get
{
return (int)y;
}
set
{
y=(double)value;
}
}
public PointD(double x, double y)
{
this.x = x; this.y = y;
}
public override string ToString()
{
return "(" + x + ", " + y + ")";
}
public static PointD Random(int w, int h)
{
return new PointD(rnd.Next(w), rnd.Next(h));
}
public bool Equals(PointD p2)
{
return x == p2.x && y == p2.y;
}
public override bool Less(Ordered o2)
{
PointD p2 = (PointD)o2;
return x < p2.x || x == p2.x && y < p2.y;
}
// Twice the signed area of the triangle (p0, p1, p2)
public static double Area2(PointD p0, PointD p1, PointD p2)
{
return p0.x * (p1.y-p2.y) + p1.x * (p2.y-p0.y) + p2.x * (p0.y-p1.y);
}
}
// ------------------------------------------------------------
// Circular doubly linked lists of PointD
class CDLL
{
private CDLL prev, next; // not null, except in deleted elements
public PointD val;
// A new CDLL node is a one-element circular list
public CDLL(PointD val)
{
this.val = val; next = prev = this;
}
public CDLL Prev
{
get { return prev; }
}
public CDLL Next
{
get { return next; }
}
// Delete: adjust the remaining elements, make this one PointD nowhere
public void Delete()
{
next.prev = prev; prev.next = next;
next = prev = null;
}
public CDLL Prepend(CDLL elt)
{
elt.next = this; elt.prev = prev; prev.next = elt; prev = elt;
return elt;
}
public CDLL Append(CDLL elt)
{
elt.prev = this; elt.next = next; next.prev = elt; next = elt;
return elt;
}
public int Size()
{
int count = 0;
CDLL node = this;
do
{
count++;
node = node.next;
} while (node != this);
return count;
}
public void PrintFwd()
{
CDLL node = this;
do
{
Console.WriteLine(node.val);
node = node.next;
} while (node != this);
Console.WriteLine();
}
public void CopyInto(PointD[] vals, int i)
{
CDLL node = this;
do
{
vals[i++] = node.val; // still, implicit checkcasts at runtime
node = node.next;
} while (node != this);
}
}
// ------------------------------------------------------------
class Polysort
{
private static void swap(PointD[] arr, int s, int t)
{
PointD tmp = arr[s]; arr[s] = arr[t]; arr[t] = tmp;
}
private static void swap(Ordered[] arr, int s, int t)
{
Ordered tmp = arr[s]; arr[s] = arr[t]; arr[t] = tmp;
}
// Typed OO-style quicksort a la Hoare/Wirth
private static void qsort(Ordered[] arr, int a, int b)
{
// sort arr[a..b]
if (a < b)
{
int i = a, j = b;
PointD x = (PointD)(arr[(i+j) / 2]);
do
{
while (arr[i].Less(x)) i++;
while (x.Less(arr[j])) j--;
if (i <= j)
{
swap(arr, i, j);
i++; j--;
}
} while (i <= j);
qsort(arr, a, j);
qsort(arr, i, b);
}
}
public static void Quicksort(Ordered[] arr)
{
qsort(arr, 0, arr.Length-1);
}
}
public abstract class Ordered
{
public abstract bool Less(Ordered that);
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 SCG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A bag collection based on a hash table of (item,count) pairs.
/// </summary>
[Serializable]
public class HashBag<T> : CollectionBase<T>, ICollection<T>
{
#region Fields
HashSet<KeyValuePair<T, int>> dict;
#endregion
#region Events
/// <summary>
///
/// </summary>
/// <value></value>
public override EventTypeEnum ListenableEvents { get { return EventTypeEnum.Basic; } }
#endregion
#region Constructors
/// <summary>
/// Create a hash bag with the deafult item equalityComparer.
/// </summary>
public HashBag() : this(EqualityComparer<T>.Default) { }
/// <summary>
/// Create a hash bag with an external item equalityComparer.
/// </summary>
/// <param name="itemequalityComparer">The external item equalityComparer.</param>
public HashBag(SCG.IEqualityComparer<T> itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet<KeyValuePair<T, int>>(new KeyValuePairEqualityComparer<T, int>(itemequalityComparer));
}
/// <summary>
/// Create a hash bag with external item equalityComparer, prescribed initial table size and default fill threshold (66%)
/// </summary>
/// <param name="capacity">Initial table size (rounded to power of 2, at least 16)</param>
/// <param name="itemequalityComparer">The external item equalityComparer</param>
public HashBag(int capacity, SCG.IEqualityComparer<T> itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet<KeyValuePair<T, int>>(capacity, new KeyValuePairEqualityComparer<T, int>(itemequalityComparer));
}
/// <summary>
/// Create a hash bag with external item equalityComparer, prescribed initial table size and fill threshold.
/// </summary>
/// <param name="capacity">Initial table size (rounded to power of 2, at least 16)</param>
/// <param name="fill">Fill threshold (valid range 10% to 90%)</param>
/// <param name="itemequalityComparer">The external item equalityComparer</param>
public HashBag(int capacity, double fill, SCG.IEqualityComparer<T> itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet<KeyValuePair<T, int>>(capacity, fill, new KeyValuePairEqualityComparer<T, int>(itemequalityComparer));
}
#endregion
#region IEditableCollection<T> Members
/// <summary>
/// The complexity of the Contains operation
/// </summary>
/// <value>Always returns Speed.Constant</value>
public virtual Speed ContainsSpeed { get { return Speed.Constant; } }
/// <summary>
/// Check if an item is in the bag
/// </summary>
/// <param name="item">The item to look for</param>
/// <returns>True if bag contains item</returns>
public virtual bool Contains(T item)
{
return dict.Contains(new KeyValuePair<T, int>(item, 0));
}
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag and
/// if so report the actual item object found.
/// </summary>
/// <param name="item">On entry, the item to look for.
/// On exit the item found, if any</param>
/// <returns>True if bag contains item</returns>
public virtual bool Find(ref T item)
{
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
item = p.Key;
return true;
}
return false;
}
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag and
/// if so replace the item object in the bag with the supplied one.
/// </summary>
/// <param name="item">The item object to update with</param>
/// <returns>True if item was found (and updated)</returns>
public virtual bool Update(T item)
{ T olditem = default(T); return Update(item, out olditem); }
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <param name="olditem"></param>
/// <returns></returns>
public virtual bool Update(T item, out T olditem)
{
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item, 0);
updatecheck();
//Note: we cannot just do dict.Update: we have to lookup the count before we
//know what to update with. There is of course a way around if we use the
//implementation of hashset -which we do not want to do.
//The hashbag is moreover mainly a proof of concept
if (dict.Find(ref p))
{
olditem = p.Key;
p.Key = item;
dict.Update(p);
if (ActiveEvents != 0)
raiseForUpdate(item, olditem, p.Value);
return true;
}
olditem = default(T);
return false;
}
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag.
/// If found, report the actual item object in the bag,
/// else add the supplied one.
/// </summary>
/// <param name="item">On entry, the item to look for or add.
/// On exit the actual object found, if any.</param>
/// <returns>True if item was found</returns>
public virtual bool FindOrAdd(ref T item)
{
updatecheck();
if (Find(ref item))
return true;
Add(item);
return false;
}
/// <summary>
/// Check if an item (collection equal to a supplied one) is in the bag and
/// if so replace the item object in the set with the supplied one; else
/// add the supplied one.
/// </summary>
/// <param name="item">The item to look for and update or add</param>
/// <returns>True if item was updated</returns>
public virtual bool UpdateOrAdd(T item)
{
updatecheck();
if (Update(item))
return true;
Add(item);
return false;
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <param name="olditem"></param>
/// <returns></returns>
public virtual bool UpdateOrAdd(T item, out T olditem)
{
updatecheck();
if (Update(item, out olditem))
return true;
Add(item);
return false;
}
/// <summary>
/// Remove one copy af an item from the bag
/// </summary>
/// <param name="item">The item to remove</param>
/// <returns>True if item was (found and) removed </returns>
public virtual bool Remove(T item)
{
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item, 0);
updatecheck();
if (dict.Find(ref p))
{
size--;
if (p.Value == 1)
dict.Remove(p);
else
{
p.Value--;
dict.Update(p);
}
if (ActiveEvents != 0)
raiseForRemove(p.Key);
return true;
}
return false;
}
/// <summary>
/// Remove one copy of an item from the bag, reporting the actual matching item object.
/// </summary>
/// <param name="item">The value to remove.</param>
/// <param name="removeditem">The removed value.</param>
/// <returns>True if item was found.</returns>
public virtual bool Remove(T item, out T removeditem)
{
updatecheck();
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
removeditem = p.Key;
size--;
if (p.Value == 1)
dict.Remove(p);
else
{
p.Value--;
dict.Update(p);
}
if (ActiveEvents != 0)
raiseForRemove(removeditem);
return true;
}
removeditem = default(T);
return false;
}
/// <summary>
/// Remove all items in a supplied collection from this bag, counting multiplicities.
/// </summary>
/// <param name="items">The items to remove.</param>
public virtual void RemoveAll(SCG.IEnumerable<T> items)
{
#warning Improve if items is a counting bag
updatecheck();
bool mustRaise = (ActiveEvents & (EventTypeEnum.Changed | EventTypeEnum.Removed)) != 0;
RaiseForRemoveAllHandler raiseHandler = mustRaise ? new RaiseForRemoveAllHandler(this) : null;
foreach (T item in items)
{
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
size--;
if (p.Value == 1)
dict.Remove(p);
else
{
p.Value--;
dict.Update(p);
}
if (mustRaise)
raiseHandler.Remove(p.Key);
}
}
if (mustRaise)
raiseHandler.Raise();
}
/// <summary>
/// Remove all items from the bag, resetting internal table to initial size.
/// </summary>
public virtual void Clear()
{
updatecheck();
if (size == 0)
return;
dict.Clear();
int oldsize = size;
size = 0;
if ((ActiveEvents & EventTypeEnum.Cleared) != 0)
raiseCollectionCleared(true, oldsize);
if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
/// <summary>
/// Remove all items *not* in a supplied collection from this bag,
/// counting multiplicities.
/// </summary>
/// <param name="items">The items to retain</param>
public virtual void RetainAll(SCG.IEnumerable<T> items)
{
updatecheck();
HashBag<T> res = new HashBag<T>(itemequalityComparer);
foreach (T item in items)
{
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item);
if (dict.Find(ref p))
{
KeyValuePair<T, int> q = p;
if (res.dict.Find(ref q))
{
if (q.Value < p.Value)
{
q.Value++;
res.dict.Update(q);
res.size++;
}
}
else
{
q.Value = 1;
res.dict.Add(q);
res.size++;
}
}
}
if (size == res.size)
return;
CircularQueue<T> wasRemoved = null;
if ((ActiveEvents & EventTypeEnum.Removed) != 0)
{
wasRemoved = new CircularQueue<T>();
foreach (KeyValuePair<T, int> p in dict)
{
int removed = p.Value - res.ContainsCount(p.Key);
if (removed > 0)
#warning We could send bag events here easily using a CircularQueue of (should?)
for (int i = 0; i < removed; i++)
wasRemoved.Enqueue(p.Key);
}
}
dict = res.dict;
size = res.size;
if ((ActiveEvents & EventTypeEnum.Removed) != 0)
raiseForRemoveAll(wasRemoved);
else if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
/// <summary>
/// Check if all items in a supplied collection is in this bag
/// (counting multiplicities).
/// </summary>
/// <param name="items">The items to look for.</param>
/// <returns>True if all items are found.</returns>
public virtual bool ContainsAll(SCG.IEnumerable<T> items)
{
HashBag<T> res = new HashBag<T>(itemequalityComparer);
foreach (T item in items)
if (res.ContainsCount(item) < ContainsCount(item))
res.Add(item);
else
return false;
return true;
}
/// <summary>
/// Create an array containing all items in this bag (in enumeration order).
/// </summary>
/// <returns>The array</returns>
public override T[] ToArray()
{
T[] res = new T[size];
int ind = 0;
foreach (KeyValuePair<T, int> p in dict)
for (int i = 0; i < p.Value; i++)
res[ind++] = p.Key;
return res;
}
/// <summary>
/// Count the number of times an item is in this set.
/// </summary>
/// <param name="item">The item to look for.</param>
/// <returns>The count</returns>
public virtual int ContainsCount(T item)
{
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
return p.Value;
return 0;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<T> UniqueItems() { return new DropMultiplicity<T>(dict); }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<KeyValuePair<T, int>> ItemMultiplicities()
{
return new GuardedCollectionValue<KeyValuePair<T, int>>(dict);
}
/// <summary>
/// Remove all copies of item from this set.
/// </summary>
/// <param name="item">The item to remove</param>
public virtual void RemoveAllCopies(T item)
{
updatecheck();
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
size -= p.Value;
dict.Remove(p);
if ((ActiveEvents & EventTypeEnum.Removed) != 0)
raiseItemsRemoved(p.Key, p.Value);
if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Copy the items of this bag to part of an array.
/// <exception cref="ArgumentOutOfRangeException"/> if i is negative.
/// <exception cref="ArgumentException"/> if the array does not have room for the items.
/// </summary>
/// <param name="array">The array to copy to</param>
/// <param name="index">The starting index.</param>
public override void CopyTo(T[] array, int index)
{
if (index < 0 || index + Count > array.Length)
throw new ArgumentOutOfRangeException();
foreach (KeyValuePair<T, int> p in dict)
for (int j = 0; j < p.Value; j++)
array[index++] = p.Key;
}
#endregion
#region IExtensible<T> Members
/// <summary>
/// Report if this is a set collection.
/// </summary>
/// <value>Always true</value>
public virtual bool AllowsDuplicates { get { return true; } }
/// <summary>
/// By convention this is true for any collection with set semantics.
/// </summary>
/// <value>True if only one representative of a group of equal items
/// is kept in the collection together with the total count.</value>
public virtual bool DuplicatesByCounting { get { return true; } }
/// <summary>
/// Add an item to this bag.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>Always true</returns>
public virtual bool Add(T item)
{
updatecheck();
add(ref item);
if (ActiveEvents != 0)
raiseForAdd(item);
return true;
}
/// <summary>
/// Add an item to this bag.
/// </summary>
/// <param name="item">The item to add.</param>
void SCG.ICollection<T>.Add(T item)
{
Add(item);
}
private void add(ref T item)
{
KeyValuePair<T, int> p = new KeyValuePair<T, int>(item, 1);
if (dict.Find(ref p))
{
p.Value++;
dict.Update(p);
item = p.Key;
}
else
dict.Add(p);
size++;
}
/// <summary>
/// Add the elements from another collection with a more specialized item type
/// to this collection.
/// </summary>
/// <param name="items">The items to add</param>
public virtual void AddAll(SCG.IEnumerable<T> items)
{
updatecheck();
#warning We could easily raise bag events
bool mustRaiseAdded = (ActiveEvents & EventTypeEnum.Added) != 0;
CircularQueue<T> wasAdded = mustRaiseAdded ? new CircularQueue<T>() : null;
bool wasChanged = false;
foreach (T item in items)
{
T jtem = item;
add(ref jtem);
wasChanged = true;
if (mustRaiseAdded)
wasAdded.Enqueue(jtem);
}
if (!wasChanged)
return;
if (mustRaiseAdded)
foreach (T item in wasAdded)
raiseItemsAdded(item, 1);
if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Choose some item of this collection.
/// </summary>
/// <exception cref="NoSuchItemException">if collection is empty.</exception>
/// <returns></returns>
public override T Choose()
{
return dict.Choose().Key;
}
/// <summary>
/// Create an enumerator for this bag.
/// </summary>
/// <returns>The enumerator</returns>
public override SCG.IEnumerator<T> GetEnumerator()
{
int left;
int mystamp = stamp;
foreach (KeyValuePair<T, int> p in dict)
{
left = p.Value;
while (left > 0)
{
if (mystamp != stamp)
throw new CollectionModifiedException();
left--;
yield return p.Key;
}
}
}
#endregion
#region ICloneable Members
/// <summary>
/// Make a shallow copy of this HashBag.
/// </summary>
/// <returns></returns>
public virtual object Clone()
{
//TODO: make sure this
HashBag<T> clone = new HashBag<T>(dict.Count > 0 ? dict.Count : 1, itemequalityComparer);
//TODO: make sure this really adds in the counting bag way!
clone.AddAll(this);
return clone;
}
#endregion
#region Diagnostics
/// <summary>
/// Test internal structure of data (invariants)
/// </summary>
/// <returns>True if pass</returns>
public virtual bool Check()
{
bool retval = dict.Check();
int count = 0;
foreach (KeyValuePair<T, int> p in dict)
count += p.Value;
if (count != size)
{
Logger.Log(string.Format("count({0}) != size({1})", count, size));
retval = false;
}
return retval;
}
#endregion
}
}
| |
using LambdicSql.ConverterServices;
using LambdicSql.ConverterServices.SymbolConverters;
namespace LambdicSql.SqlServer
{
public static partial class Symbol
{
/// <summary>
/// ABS function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/abs-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>Absolute value.</returns>
[FuncStyleConverter]
public static decimal Abs(decimal numeric_expression) { throw new InvalitContextException(nameof(Abs)); }
/// <summary>
/// ACOS function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/acos-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>ACOS value.</returns>
[FuncStyleConverter]
public static double Acos(double float_expression) { throw new InvalitContextException(nameof(Acos)); }
/// <summary>
/// ASIN function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/asin-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>summary value.</returns>
[FuncStyleConverter]
public static double Asin(double float_expression) { throw new InvalitContextException(nameof(Asin)); }
/// <summary>
/// ATAN function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/atan-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>ATAN value.</returns>
[FuncStyleConverter]
public static double Atan(double float_expression) { throw new InvalitContextException(nameof(Atan)); }
/// <summary>
/// ATN2 function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/atn2-transact-sql
/// </summary>
/// <param name="float_expression1">The column or expression that is function target.</param>
/// <param name="float_expression2">The column or expression that is function target.</param>
/// <returns>ATN2 value.</returns>
[FuncStyleConverter]
public static double Atn2(double float_expression1, double float_expression2) { throw new InvalitContextException(nameof(Atn2)); }
/// <summary>
/// CEILING function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/ceiling-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>CEILING value.</returns>
[FuncStyleConverter]
public static decimal Ceiling(decimal numeric_expression) { throw new InvalitContextException(nameof(Ceiling)); }
/// <summary>
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/cos-transact-sql
/// COS function.
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>COS value.</returns>
[FuncStyleConverter]
public static double Cos(double float_expression) { throw new InvalitContextException(nameof(Cos)); }
/// <summary>
/// COT function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/cot-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>COT value.</returns>
[FuncStyleConverter]
public static double Cot(double float_expression) { throw new InvalitContextException(nameof(Cot)); }
/// <summary>
/// DEGREES function.
/// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/degrees-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>DEGREES value.</returns>
[FuncStyleConverter]
public static decimal Degrees(decimal numeric_expression) { throw new InvalitContextException(nameof(Degrees)); }
/// <summary>
/// EXP function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/exp-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>EXP value.</returns>
[FuncStyleConverter]
public static double Exp(double float_expression) { throw new InvalitContextException(nameof(Ceiling)); }
/// <summary>
/// FLOOR function.
/// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/floor-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>FLOOR value.</returns>
[FuncStyleConverter]
public static decimal Floor(decimal numeric_expression) { throw new InvalitContextException(nameof(Floor)); }
/// <summary>
/// LOG function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/log-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>LOG value.</returns>
[FuncStyleConverter]
public static double Log(double float_expression) { throw new InvalitContextException(nameof(Log)); }
/// <summary>
/// LOG10 function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/log10-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>LOG10 value.</returns>
[FuncStyleConverter]
public static double Log10(double float_expression) { throw new InvalitContextException(nameof(Log10)); }
/// <summary>
/// PI function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/pi-transact-sql
/// </summary>
/// <returns>PI value.</returns>
[FuncStyleConverter]
public static double PI() { throw new InvalitContextException(nameof(Log)); }
/// <summary>
/// POWER function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/power-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <param name="y">The column or expression that is function target.</param>
/// <returns>POWER value.</returns>
[FuncStyleConverter]
public static double Power(double float_expression, int y) { throw new InvalitContextException(nameof(Log)); }
/// <summary>
/// RADIANS function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/radians-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>RADIANS value.</returns>
[FuncStyleConverter]
public static decimal Radians(decimal numeric_expression) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// RAND function.
/// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/rand-transact-sql
/// </summary>
/// <param name="seed">seed value.</param>
/// <returns>RAND value.</returns>
[FuncStyleConverter]
public static double Rand(int seed) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// ROUND function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/round-transact-sql
/// </summary>
/// <param name="target">Numeric expression to round.</param>
/// <param name="digit">Is the precision to which it is to be rounded.</param>
/// <returns>Rounded result.</returns>
[FuncStyleConverter]
public static T1 Round<T1, T2>(T1 target, T2 digit) { throw new InvalitContextException(nameof(Round)); }
/// <summary>
/// ROUND function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/round-transact-sql
/// </summary>
/// <param name="target">Numeric expression to round.</param>
/// <param name="digit">Is the precision to which it is to be rounded.</param>
/// <returns>Rounded result.</returns>
[FuncStyleConverter]
public static long Round(long target, int digit) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// ROUND function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/round-transact-sql
/// </summary>
/// <param name="target">Numeric expression to round.</param>
/// <param name="digit">Is the precision to which it is to be rounded.</param>
/// <returns>Rounded result.</returns>
[FuncStyleConverter]
public static int Round(int target, int digit) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// ROUND function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/round-transact-sql
/// </summary>
/// <param name="target">Numeric expression to round.</param>
/// <param name="digit">Is the precision to which it is to be rounded.</param>
/// <returns>Rounded result.</returns>
[FuncStyleConverter]
public static decimal Round(decimal target, int digit) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// ROUND function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/round-transact-sql
/// </summary>
/// <param name="target">Numeric expression to round.</param>
/// <param name="digit">Is the precision to which it is to be rounded.</param>
/// <returns>Rounded result.</returns>
[FuncStyleConverter]
public static double Round(double target, int digit) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// SIGN function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sign-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>SIGN value.</returns>
[FuncStyleConverter]
public static long Sign(long numeric_expression) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// SIGN function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sign-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>SIGN value.</returns>
[FuncStyleConverter]
public static int Sign(int numeric_expression) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// SIGN function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sign-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>SIGN value.</returns>
[FuncStyleConverter]
public static decimal Sign(decimal numeric_expression) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// SIGN function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sign-transact-sql
/// </summary>
/// <param name="numeric_expression">The column or expression that is function target.</param>
/// <returns>SIGN value.</returns>
[FuncStyleConverter]
public static double Sign(double numeric_expression) { throw new InvalitContextException(nameof(Sign)); }
/// <summary>
/// SIN function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sin-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>SIN value.</returns>
[FuncStyleConverter]
public static double Sin(double float_expression) { throw new InvalitContextException(nameof(Sin)); }
/// <summary>
/// SQRT function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sqrt-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>SQRT value.</returns>
[FuncStyleConverter]
public static double Sqrt(double float_expression) { throw new InvalitContextException(nameof(Log)); }
/// <summary>
/// SQUARE function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/square-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>SQUARE value.</returns>
[FuncStyleConverter]
public static double Square(double float_expression) { throw new InvalitContextException(nameof(Log)); }
/// <summary>
/// TAN function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/tan-transact-sql
/// </summary>
/// <param name="float_expression">The column or expression that is function target.</param>
/// <returns>TAN value.</returns>
[FuncStyleConverter]
public static double Tan(double float_expression) { throw new InvalitContextException(nameof(Tan)); }
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Talent.V4
{
/// <summary>Settings for <see cref="CompletionClient"/> instances.</summary>
public sealed partial class CompletionSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CompletionSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CompletionSettings"/>.</returns>
public static CompletionSettings GetDefault() => new CompletionSettings();
/// <summary>Constructs a new <see cref="CompletionSettings"/> object with default settings.</summary>
public CompletionSettings()
{
}
private CompletionSettings(CompletionSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CompleteQuerySettings = existing.CompleteQuerySettings;
OnCopy(existing);
}
partial void OnCopy(CompletionSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CompletionClient.CompleteQuery</c> and <c>CompletionClient.CompleteQueryAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.DeadlineExceeded"/>,
/// <see cref="grpccore::StatusCode.Unavailable"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 30 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CompleteQuerySettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(30000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CompletionSettings"/> object.</returns>
public CompletionSettings Clone() => new CompletionSettings(this);
}
/// <summary>
/// Builder class for <see cref="CompletionClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class CompletionClientBuilder : gaxgrpc::ClientBuilderBase<CompletionClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CompletionSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CompletionClientBuilder()
{
UseJwtAccessWithScopes = CompletionClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CompletionClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CompletionClient> task);
/// <summary>Builds the resulting client.</summary>
public override CompletionClient Build()
{
CompletionClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CompletionClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CompletionClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CompletionClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CompletionClient.Create(callInvoker, Settings);
}
private async stt::Task<CompletionClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CompletionClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CompletionClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CompletionClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CompletionClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>Completion client wrapper, for convenient use.</summary>
/// <remarks>
/// A service handles auto completion.
/// </remarks>
public abstract partial class CompletionClient
{
/// <summary>
/// The default endpoint for the Completion service, which is a host of "jobs.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "jobs.googleapis.com:443";
/// <summary>The default Completion scopes.</summary>
/// <remarks>
/// The default Completion scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/jobs</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/jobs",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CompletionClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="CompletionClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CompletionClient"/>.</returns>
public static stt::Task<CompletionClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CompletionClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CompletionClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="CompletionClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CompletionClient"/>.</returns>
public static CompletionClient Create() => new CompletionClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CompletionClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CompletionSettings"/>.</param>
/// <returns>The created <see cref="CompletionClient"/>.</returns>
internal static CompletionClient Create(grpccore::CallInvoker callInvoker, CompletionSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Completion.CompletionClient grpcClient = new Completion.CompletionClient(callInvoker);
return new CompletionClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC Completion client</summary>
public virtual Completion.CompletionClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual CompleteQueryResponse CompleteQuery(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, st::CancellationToken cancellationToken) =>
CompleteQueryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>Completion client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service handles auto completion.
/// </remarks>
public sealed partial class CompletionClientImpl : CompletionClient
{
private readonly gaxgrpc::ApiCall<CompleteQueryRequest, CompleteQueryResponse> _callCompleteQuery;
/// <summary>
/// Constructs a client wrapper for the Completion service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CompletionSettings"/> used within this client.</param>
public CompletionClientImpl(Completion.CompletionClient grpcClient, CompletionSettings settings)
{
GrpcClient = grpcClient;
CompletionSettings effectiveSettings = settings ?? CompletionSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCompleteQuery = clientHelper.BuildApiCall<CompleteQueryRequest, CompleteQueryResponse>(grpcClient.CompleteQueryAsync, grpcClient.CompleteQuery, effectiveSettings.CompleteQuerySettings).WithGoogleRequestParam("tenant", request => request.Tenant);
Modify_ApiCall(ref _callCompleteQuery);
Modify_CompleteQueryApiCall(ref _callCompleteQuery);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CompleteQueryApiCall(ref gaxgrpc::ApiCall<CompleteQueryRequest, CompleteQueryResponse> call);
partial void OnConstruction(Completion.CompletionClient grpcClient, CompletionSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Completion client</summary>
public override Completion.CompletionClient GrpcClient { get; }
partial void Modify_CompleteQueryRequest(ref CompleteQueryRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override CompleteQueryResponse CompleteQuery(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CompleteQueryRequest(ref request, ref callSettings);
return _callCompleteQuery.Sync(request, callSettings);
}
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CompleteQueryRequest(ref request, ref callSettings);
return _callCompleteQuery.Async(request, callSettings);
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace Infragistics.ToyBox
{
/// <summary>
/// This class contains all of the different types of equations
/// </summary>
public static class WPFpenner
{
/*
Easing Equations (c) 2003 Robert Penner, all rights reserved.
This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html.
*/
/// <summary>
/// This performs the Ease Out Elastic Equation (decelerating to the newVal with elastic like movement)
/// </summary>
/// <param name="time">The current time</param>
/// <param name="startVal">The beginning value</param>
/// <param name="newVal">The change in value</param>
/// <param name="duration">The duration of time</param>
/// <returns></returns>
public static double easeOutElastic(double time, double startVal, double newVal, double duration)
{
if ((time /= duration) == 1) return startVal + newVal;
double p = duration * .3;
double s = p / 4;
return (newVal * Math.Pow(2, -10 * time) * Math.Sin((time * duration - s) * (2 * Math.PI) / p) + newVal + startVal);
}
public static double easeInElastic(double time, double startVal, double newVal, double duration)
{
if ((time /= duration) == 1) return startVal + newVal;
double p = duration * .3;
double s = p / 4;
return -(newVal * Math.Pow(2, 10 * (time -= 1)) * Math.Sin((time * duration - s) * (2 * Math.PI) / p)) + startVal;
}
public static double easeInOutElastic(double time, double startVal, double newVal, double duration)
{
if ((time /= duration / 2) == 2) return startVal + newVal;
double p = duration * (.3 * 1.5);
double s = p / 4;
if (time < 1) return -.5 * (newVal * Math.Pow(2, 10 * (time -= 1)) * Math.Sin((time * duration - s) * (2 * Math.PI) / p)) + startVal;
return newVal * Math.Pow(2, -10 * (time -= 1)) * Math.Sin((time * duration - s) * (2 * Math.PI) / p) * .5 + newVal + startVal;
}
public static double easeOutBounce(double time, double startVal, double newVal, double duration)
{
if ((time /= duration) < (1 / 2.75)) return newVal * (7.5625 * time * time) + startVal;
else if (time < (2 / 2.75)) return newVal * (7.5625 * (time -= (1.5 / 2.75)) * time + .75) + startVal;
else if (time < (2.5 / 2.75)) return newVal * (7.5625 * (time -= (2.25 / 2.75)) * time + .9375) + startVal;
else return newVal * (7.5625 * (time -= (2.625 / 2.75)) * time + .984375) + startVal;
}
public static double easeInBounce(double time, double startVal, double newVal, double duration)
{
if ((time /= duration) < (1 / 2.75)) return newVal * (7.5625 * time * time) + startVal;
else if (time < (2 / 2.75)) return newVal * (7.5625 * (time -= (1.5 / 2.75)) * time + .75) + startVal;
else if (time < (2.5 / 2.75)) return newVal * (7.5625 * (time -= (2.25 / 2.75)) * time + .9375) + startVal;
else return newVal * (7.5625 * (time -= (2.625 / 2.75)) * time + .984375) + startVal;
// return newVal - easeOutBounce(duration - time, 0, newVal, duration) + startVal;
}
public static double easeInOutBounce(double time, double startVal, double newVal, double duration)
{
if (time < duration / 2) return easeInBounce(time * 2, 0, newVal, duration) * .5 + startVal;
else return easeOutBounce(time * 2 - duration, 0, newVal, duration) * .5 + newVal * .5 + startVal;
}
public static double easeOutExpo(double time, double startVal, double newVal, double duration)
{
return (time == duration) ? startVal + newVal : newVal * (-Math.Pow(2, -10 * time / duration) + 1) + startVal;
}
public static double easeInExpo(double time, double startVal, double newVal, double duration)
{
return (time == 0) ? startVal : newVal * Math.Pow(2, 10 * (time / duration - 1)) + startVal;
}
public static double easeInOutExpo(double time, double startVal, double newVal, double duration)
{
if (time == 0) return startVal;
if (time == duration) return startVal + newVal;
if ((time /= duration / 2) < 1) return newVal / 2 * Math.Pow(2, 10 * (time - 1)) + startVal;
return newVal / 2 * (-Math.Pow(2, -10 * --time) + 2) + startVal;
}
public static double easeOutQuad(double time, double startVal, double newVal, double duration)
{
return -newVal * (time /= duration) * (time - 2) + startVal;
}
public static double easeInQuad(double time, double startVal, double newVal, double duration)
{
return newVal * (time /= duration) * time + startVal;
}
public static double easeInOutQuad(double time, double startVal, double newVal, double duration)
{
if ((time /= duration / 2) < 1) return newVal / 2 * time * time + startVal;
return -newVal / 2 * ((--time) * (time - 2) - 1) + startVal;
}
public static double easeOutSine(double time, double startVal, double newVal, double duration)
{
return newVal * Math.Sin(time / duration * (Math.PI / 2)) + startVal;
}
public static double easeInSine(double time, double startVal, double newVal, double duration)
{
return -newVal * Math.Cos(time / duration * (Math.PI / 2)) + newVal + startVal;
}
public static double easeInOutSine(double time, double startVal, double newVal, double duration)
{
if ((time /= duration / 2) < 1) return newVal / 2 * (Math.Sin(Math.PI * time / 2)) + startVal;
return -newVal / 2 * (Math.Cos(Math.PI * --time / 2) - 2) + startVal;
}
public static double easeOutCirc(double time, double startVal, double newVal, double duration)
{
return newVal * Math.Sqrt(1 - (time = time / duration - 1) * time) + startVal;
}
public static double easeInCirc(double time, double startVal, double newVal, double duration)
{
return -newVal * (Math.Sqrt(1 - (time /= duration) * time) - 1) + startVal;
}
public static double easeInOutCirc(double time, double startVal, double newVal, double duration)
{
if ((time /= duration / 2) < 1) return -newVal / 2 * (Math.Sqrt(1 - time * time) - 1) + startVal;
return newVal / 2 * (Math.Sqrt(1 - (time -= 2) * time) + 1) + startVal;
}
public static double easeOutCubic(double time, double startVal, double newVal, double duration)
{
return newVal * ((time = time / duration - 1) * time * time + 1) + startVal;
}
public static double easeInCubic(double time, double startVal, double newVal, double duration)
{
return newVal * (time /= duration) * time * time + startVal;
}
public static double easeInOutCubic(double time, double startVal, double newVal, double duration)
{
if ((time /= duration / 2) < 1) return newVal / 2 * time * time * time + startVal;
return newVal / 2 * ((time -= 2) * time * time + 2) + startVal;
}
public static double easeOutQuint(double time, double startVal, double newVal, double duration)
{
return newVal * ((time = time / duration - 1) * time * time * time * time + 1) + startVal;
}
public static double easeInQuint(double time, double startVal, double newVal, double duration)
{
return newVal * (time /= duration) * time * time * time * time + startVal;
}
public static double easeInOutQuint(double time, double startVal, double newVal, double duration)
{
if ((time /= duration / 2) < 1) return newVal / 2 * time * time * time * time * time + startVal;
return newVal / 2 * ((time -= 2) * time * time * time * time + 2) + startVal;
}
public static double easeOutBack(double time, double startVal, double newVal, double duration)
{
return newVal * ((time = time / duration - 1) * time * ((1.70158 + 1) * time + 1.70158) + 1) + startVal;
}
public static double easeInBack(double time, double startVal, double newVal, double duration)
{
return newVal * (time /= duration) * time * ((1.70158 + 1) * time - 1.70158) + startVal;
}
public static double easeInOutBack(double time, double startVal, double newVal, double duration)
{
double s = 1.70158;
if ((time /= duration / 2) < 1) return newVal / 2 * (time * time * (((s *= (1.525)) + 1) * time - s)) + startVal;
return newVal / 2 * ((time -= 2) * time * (((s *= (1.525)) + 1) * time + s) + 2) + startVal;
}
public static double easeOutQuart(double time, double startVal, double newVal, double duration)
{
return -newVal * ((time = time / duration - 1) * time * time * time - 1) + startVal;
}
public static double easeInQuart(double time, double startVal, double newVal, double duration)
{
return newVal * (time /= duration) * time * time * time + startVal;
}
public static double easeInOutQuart(double time, double startVal, double newVal, double duration)
{
if ((time /= duration / 2) < 1) return newVal / 2 * time * time * time * time + startVal;
return -newVal / 2 * ((time -= 2) * time * time * time - 2) + startVal;
}
public static double linear(double time, double startVal, double newVal, double duration)
{
return newVal * time / duration + startVal;
}
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Samples.Debugging.Native;
using Microsoft.Samples.Debugging.Native.Private;
namespace Microsoft.Samples.Debugging.Native
{
public class AMD64Context : INativeContext, IEquatable<INativeContext>, IDisposable
{
private int m_size;
private Platform m_platform;
private int m_imageFileMachine;
private IntPtr m_rawPtr;
~AMD64Context()
{
this.Dispose(false);
}
// This is a private contstructor for cloning Context objects. It should not be used outside of this class.
private AMD64Context(INativeContext ctx)
{
this.m_size = ctx.Size;
this.m_platform = ctx.Platform;
this.m_imageFileMachine = ctx.ImageFileMachine;
this.m_rawPtr = Marshal.AllocHGlobal(this.Size);
using (IContextDirectAccessor w = ctx.OpenForDirectAccess())
{
// The fact that Marshal.Copy cannot copy between to native memory locations is stupid.
for (int i = 0; i < this.m_size; i++)
{
// In theory, we could make this faster by copying larger units (i.e. Int64). We get our sizes in bytes
// so for now we'll just copy bytes to keep our units straight.
byte chunk = Marshal.ReadByte(w.RawBuffer, i);
Marshal.WriteByte(this.RawPtr, i, chunk);
}
}
}
public AMD64Context()
: this(AgnosticContextFlags.ContextControl | AgnosticContextFlags.ContextInteger)
{
}
public AMD64Context(AgnosticContextFlags aFlags)
{
InitializeContext();
WriteContextFlagsToBuffer(GetPSFlags(aFlags));
}
public AMD64Context(ContextFlags flags)
{
InitializeContext();
WriteContextFlagsToBuffer(flags);
}
private void InitializeContext()
{
this.m_size = (int)ContextSize.AMD64;
this.m_platform = Platform.AMD64;
this.m_imageFileMachine = (int)Native.ImageFileMachine.AMD64;
this.m_rawPtr = Marshal.AllocHGlobal(this.Size);
return;
}
private void WriteContextFlagsToBuffer(ContextFlags flags)
{
Debug.Assert(this.RawPtr != IntPtr.Zero);
Marshal.WriteInt32(this.RawPtr, (int)AMD64Offsets.ContextFlags, (Int32)flags);
}
public IContextDirectAccessor OpenForDirectAccess()
{
// we can return a copy of ourself so that it will be destroyed once it goes out of scope.
return new ContextAccessor(this.RawPtr, this.Size);
}
public void ClearContext()
{
// make sure that we have access to the buffer
using (IContextDirectAccessor w = this.OpenForDirectAccess())
{
for (int i = 0; i < w.Size; i++)
{
Marshal.WriteByte(w.RawBuffer, i, (byte)0);
}
}
}
// returns the platform-specific Context Flags
public ContextFlags GetPSFlags(AgnosticContextFlags flags)
{
// We know that we need an amd64 context
this.m_platform = Platform.AMD64;
ContextFlags cFlags = ContextFlags.AMD64Context;
if ((flags & AgnosticContextFlags.ContextInteger) == AgnosticContextFlags.ContextInteger)
{
// ContextInteger is the same for all platforms, so we can do a blanket |=
cFlags |= (ContextFlags)AgnosticContextFlags.ContextInteger;
}
if ((flags & AgnosticContextFlags.ContextControl) == AgnosticContextFlags.ContextControl)
{
cFlags |= (ContextFlags)AgnosticContextFlags.ContextControl;
}
if ((flags & AgnosticContextFlags.ContextFloatingPoint) == AgnosticContextFlags.ContextFloatingPoint)
{
cFlags |= (ContextFlags)AgnosticContextFlags.ContextFloatingPoint;
}
if ((flags & AgnosticContextFlags.ContextAll) == AgnosticContextFlags.ContextAll)
{
// ContextAll is the same for all platforms, so we can do a blanket |=
cFlags |= (ContextFlags)AgnosticContextFlags.ContextAll;
}
return cFlags;
}
// Sets m_platform the the platform represented by the context flags
private Platform GetPlatform(ContextFlags flags)
{
return Platform.AMD64;
}
// returns the size of the Context
public int Size
{
get
{
return this.m_size;
}
}
// returns a pointer to the Context
private IntPtr RawPtr
{
get
{
return this.m_rawPtr;
}
}
// returns the ContextFlags for the Context
public ContextFlags Flags
{
get
{
Debug.Assert(this.RawPtr != IntPtr.Zero);
return (ContextFlags)Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.ContextFlags);
}
set
{
if ((value & ContextFlags.AMD64Context) == 0)
{
throw new ArgumentException("Process architecture flag must be set");
}
if ((value & ~ContextFlags.AMD64ContextAll) != 0)
{
throw new ArgumentException("Unsupported context flags for this architecture");
}
WriteContextFlagsToBuffer(value);
}
}
// returns the StackPointer for the Context
public IntPtr StackPointer
{
get
{
Debug.Assert(this.m_rawPtr != IntPtr.Zero, "The context has an invalid context pointer");
return (IntPtr)Marshal.ReadInt64(this.m_rawPtr, (int)AMD64Offsets.Rsp);
}
}
// returns a Platform for the Context
public Platform Platform
{
get
{
return this.m_platform;
}
}
// returns the IP for the Context
public IntPtr InstructionPointer
{
get
{
IntPtr ip = IntPtr.Zero;
using (IContextDirectAccessor w = this.OpenForDirectAccess())
{
ip = (IntPtr)Marshal.ReadInt64(w.RawBuffer, (int)AMD64Offsets.Rip);
}
return ip;
}
set
{
using (IContextDirectAccessor w = this.OpenForDirectAccess())
{
Marshal.WriteInt64(w.RawBuffer, (int)AMD64Offsets.Rip, (Int64)value);
}
}
}
// returns the ImageFileMachine for the Context
public int ImageFileMachine
{
get
{
return this.m_imageFileMachine;
}
}
public void SetSingleStepFlag(bool fEnable)
{
if (fEnable)
{
int eflags = Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.EFlags) | (int)AMD64Flags.SINGLE_STEP_FLAG;
Marshal.WriteInt32(this.RawPtr, (int)AMD64Offsets.EFlags, eflags);
}
else
{
int eflags = Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.EFlags) & ~((int)AMD64Flags.SINGLE_STEP_FLAG);
Marshal.WriteInt32(this.RawPtr, (int)AMD64Offsets.EFlags, eflags);
}
}
public bool IsSingleStepFlagEnabled
{
get
{
return ((Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.EFlags) & (int)AMD64Flags.SINGLE_STEP_FLAG) != 0);
}
}
public INativeContext Clone()
{
return new AMD64Context(this);
}
public bool Equals(INativeContext other)
{
if (this.Platform != other.Platform)
{
return false;
}
if (this.ImageFileMachine != other.ImageFileMachine)
{
return false;
}
if (this.Size != other.Size)
{
return false;
}
return CheckContexts(this, (AMD64Context)other);
}
public bool CheckContexts(INativeContext a1, INativeContext a2)
{
return CheckAMD64Contexts((AMD64Context)a1, (AMD64Context)a2);
}
// compare a chuck of the context record contained between the two offsets
private bool CheckContextChunk(AMD64Context a1, AMD64Context a2, int startOffset, int endOffset)
{
using (IContextDirectAccessor c1 = a1.OpenForDirectAccess())
{
using (IContextDirectAccessor c2 = a2.OpenForDirectAccess())
{
for (int i = startOffset; i < endOffset; i++)
{
if (Marshal.ReadByte(c1.RawBuffer, i) != Marshal.ReadByte(c2.RawBuffer, i))
{
return false;
}
}
}
}
return true;
}
private bool CheckAMD64Contexts(AMD64Context a1, AMD64Context a2)
{
//CONTEXT_CONTROL contains: SegCs, SegSs, EFlags, Rsp, Rip
if ((a1.Flags & ContextFlags.AMD64ContextControl) == ContextFlags.AMD64ContextControl)
{
if (!CheckContextChunk(a1, a2, (int)AMD64Offsets.SegCs, (int)AMD64Offsets.SegDs) ||
!CheckContextChunk(a1, a2, (int)AMD64Offsets.SegSs, (int)AMD64Offsets.Dr0) ||
!CheckContextChunk(a1, a2, (int)AMD64Offsets.Rsp, (int)AMD64Offsets.Rbp) ||
!CheckContextChunk(a1, a2, (int)AMD64Offsets.Rip, (int)AMD64Offsets.FltSave))
{
return false;
}
}
// CONTEXT_INTEGER contains: Rax, Rcx, Rdx, Rbx, Rbp, Rsi, Rdi, R8-R15
if ((a1.Flags & ContextFlags.AMD64ContextInteger) == ContextFlags.AMD64ContextInteger)
{
if (!CheckContextChunk(a1, a2, (int)AMD64Offsets.Rax, (int)AMD64Offsets.Rsp) ||
!CheckContextChunk(a1, a2, (int)AMD64Offsets.Rbp, (int)AMD64Offsets.Rip))
{
return false;
}
}
// CONTEXT_SEGMENTS contains: SegDs, SegEs, SegFs, SegGs
if ((a1.Flags & ContextFlags.AMD64ContextSegments) == ContextFlags.AMD64ContextSegments)
{
if (!CheckContextChunk(a1, a2, (int)AMD64Offsets.SegDs, (int)AMD64Offsets.SegSs))
{
return false;
}
}
//CONTEXT_DEBUG_REGISTERS contains: Dr0-Dr3, Dr6-Dr7 (these are continuous in winnt.h)
if ((a1.Flags & ContextFlags.AMD64ContextDebugRegisters) == ContextFlags.AMD64ContextDebugRegisters)
{
if (!CheckContextChunk(a1, a2, (int)AMD64Offsets.Dr0, (int)AMD64Offsets.Rax))
{
return false;
}
}
//CONTEXT_FLOATING_POINT contains: Mm0/St0-Mm7/St7, Xmm0-Xmm15
if ((a1.Flags & ContextFlags.AMD64ContextFloatingPoint) == ContextFlags.AMD64ContextFloatingPoint)
{
if (!CheckContextChunk(a1, a2, (int)AMD64Offsets.FltSave, (int)AMD64Offsets.VectorRegister))
{
return false;
}
}
return true;
}
private bool HasFlags(ContextFlags flags)
{
return ((this.Flags & flags) == flags);
}
public IEnumerable<String> EnumerateRegisters()
{
return EnumerateAMD64Registers();
}
private IEnumerable<String> EnumerateAMD64Registers()
{
List<String> list = new List<String>();
// This includes the most commonly used flags.
if (HasFlags(ContextFlags.AMD64ContextControl))
{
list.Add("Rsp");
list.Add("Rip");
list.Add("EFlags");
}
if (HasFlags(ContextFlags.AMD64ContextInteger))
{
list.Add("Rax");
list.Add("Rbx");
list.Add("Rcx");
list.Add("Rdx");
list.Add("Rsi");
list.Add("Rdi");
list.Add("Rbp");
list.Add("Rsi");
list.Add("Rdi");
list.Add("R8");
list.Add("R9");
list.Add("R10");
list.Add("R11");
list.Add("R12");
list.Add("R13");
list.Add("R14");
list.Add("R15");
}
if (HasFlags(ContextFlags.AMD64ContextSegments))
{
list.Add("SegDs");
list.Add("SegEs");
list.Add("SegFs");
list.Add("SegGs");
}
if (HasFlags(ContextFlags.AMD64ContextFloatingPoint))
{
list.Add("FltSave");
list.Add("Legacy");
list.Add("Xmm0");
list.Add("Xmm1");
list.Add("Xmm2");
list.Add("Xmm3");
list.Add("Xmm4");
list.Add("Xmm5");
list.Add("Xmm6");
list.Add("Xmm7");
list.Add("Xmm8");
list.Add("Xmm9");
list.Add("Xmm10");
list.Add("Xmm11");
list.Add("Xmm12");
list.Add("Xmm13");
list.Add("Xmm14");
list.Add("Xmm15");
}
if (HasFlags(ContextFlags.AMD64ContextDebugRegisters))
{
list.Add("Dr0");
list.Add("Dr1");
list.Add("Dr2");
list.Add("Dr3");
list.Add("Dr6");
list.Add("Dr7");
}
return list;
}
public object FindRegisterByName(String name)
{
return AMD64FindRegisterByName(name);
}
private object AMD64FindRegisterByName(String name)
{
name = name.ToUpperInvariant();
if (HasFlags(ContextFlags.AMD64ContextControl))
{
if (name == "RSP") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rsp);
if (name == "RIP") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rip);
if (name == "EFLAGS") return Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.EFlags);
}
if (HasFlags(ContextFlags.AMD64ContextInteger))
{
if (name == "RAX") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rax);
if (name == "RBX") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rbx);
if (name == "RCX") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rcx);
if (name == "RDX") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rdx);
if (name == "RSI") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rsi);
if (name == "RDI") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rdi);
if (name == "RBP") return Marshal.ReadInt64(this.RawPtr, (int)AMD64Offsets.Rbp);
}
if (HasFlags(ContextFlags.AMD64ContextSegments))
{
if (name == "SEGDS") return Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.SegDs);
if (name == "SEGES") return Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.SegEs);
if (name == "SEGFS") return Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.SegFs);
if (name == "SEGGS") return Marshal.ReadInt32(this.RawPtr, (int)AMD64Offsets.SegGs);
}
throw new InvalidOperationException(String.Format("Register '{0}' is not in the context", name));
}
public void SetRegisterByName(String name, object value)
{
AMD64SetRegisterByName(name, value);
}
private void AMD64SetRegisterByName(String name, object value)
{
name = name.ToUpperInvariant();
if (HasFlags(ContextFlags.AMD64ContextControl))
{
if (name == "RSP")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rsp, (Int64)value);
return;
}
if (name == "RIP")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rip, (Int64)value);
return;
}
if (name == "EFLAGS")
{
Marshal.WriteInt32(this.RawPtr, (int)AMD64Offsets.EFlags, (Int32)value);
return;
}
}
if (HasFlags(ContextFlags.AMD64ContextInteger))
{
if (name == "RAX")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rax, (Int64)value);
return;
}
if (name == "RBX")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rbx, (Int64)value);
return;
}
if (name == "RCX")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rcx, (Int64)value);
return;
}
if (name == "RDX")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rdx, (Int64)value);
return;
}
if (name == "RSI")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rsi, (Int64)value);
return;
}
if (name == "RDI")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rdi, (Int64)value);
return;
}
if (name == "RBP")
{
Marshal.WriteInt64(this.RawPtr, (int)AMD64Offsets.Rbp, (Int64)value);
return;
}
}
if (HasFlags(ContextFlags.AMD64ContextSegments))
{
if (name == "SEGDS")
{
Marshal.WriteInt32(this.RawPtr, (int)AMD64Offsets.SegDs, (Int32)value);
return;
}
if (name == "SEGES")
{
Marshal.WriteInt32(this.RawPtr, (int)AMD64Offsets.SegEs, (Int32)value);
return;
}
if (name == "SEGFS")
{
Marshal.WriteInt32(this.RawPtr, (int)AMD64Offsets.SegFs, (Int32)value);
return;
}
if (name == "SEGGS")
{
Marshal.WriteInt32(this.RawPtr, (int)AMD64Offsets.SegGs, (Int32)value);
return;
}
}
throw new InvalidOperationException(String.Format("Register '{0}' is not in the context", name));
}
#region IDisposable Members
public void Dispose()
{
this.Dispose(true);
}
public void Dispose(bool supressPendingFinalizer)
{
this.m_imageFileMachine = 0;
this.m_platform = Platform.None;
Marshal.FreeHGlobal(this.m_rawPtr);
this.m_size = 0;
this.m_rawPtr = IntPtr.Zero;
if (supressPendingFinalizer)
{
GC.SuppressFinalize(this);
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.