context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using FlatRedBall.Graphics.Texture;
namespace FlatRedBall.IO
{
#region XML Docs
/// <summary>
/// Class responsible for creating ImageDatas from BMP files.
/// </summary>
#endregion
public class BmpLoader
{
private struct BMPHeader
{
public uint Size;
public uint Width;
public uint Height;
public uint BitCount;
public Color[] Pixels;
}
#region Fields
#endregion
#region Properties
#endregion
#region Event Methods
#endregion
#region Methods
#region Private Methods
private static byte[] ReadFile(Stream stream)
{
int initialLength = 32768;
byte[] buffer = new byte[initialLength];
int bytesRead = 0;
int chunk = 0;
while ((chunk = stream.Read(buffer,
bytesRead,
buffer.Length - bytesRead)) > 0)
{
//update # of bytes read
bytesRead += chunk;
//if the buffer is full
if (bytesRead == buffer.Length)
{
//check if this is the end of the stream
int nextByte = stream.ReadByte();
//if so, return
if (nextByte == -1)
{
return buffer;
}
//otherwise, expand the buffer and repeat the process
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[bytesRead] = (byte)nextByte;
buffer = newBuffer;
bytesRead++;
}
}
//when done, copy into an array of the propper size and return
byte[] res = new byte[bytesRead];
Array.Copy(buffer, res, bytesRead);
return res;
}
private static byte[] LoadFile(string fileName)
{
// September 14, 2010:
// I think we can just standardize the reading of the file by simply by using
// the GetStreamForFile method instead of branching.
//#if !WINDOWS_PHONE
// System.Diagnostics.Trace.Write(Path.Combine(Microsoft.Xna.Framework.Storage.StorageContainer.TitleLocation, fileName.Replace("/", "\\")));
// FileStream file = File.OpenRead(Path.Combine(Microsoft.Xna.Framework.Storage.StorageContainer.TitleLocation, fileName.Replace("/", "\\")));
// byte[] source = ReadFile(file);
// return source;
//#else
Stream stream = FileManager.GetStreamForFile(fileName);
byte[] source = ReadFile(stream);
FileManager.Close(stream);
return source;
//#endif
}
private static bool CheckSignature(ref Stream file)
{
//2-byte .bmp signature
byte[] signature = {66, 77};
for (int i = 0; i < 2; ++i)
{
if (signature[i] != file.ReadByte())
return false;
}
return true;
}
private static void ParseBytes(ref Stream file, ref BMPHeader bmpHeader)
{
//every BMP header is 54 bytes, followed by the image data
//SIZE of the BMP: 2 bytes in (4 bytes long)
//WIDTH of the BMP: 18 bytes in (4 bytes long)...in pixels
//HEIGHT of the BMP: 22 bytes in (4 bytes long)...in pixels
//PIXELDATA starts 54 bytes in, each row is 8 bytes long
//grabs B[2,3,4,5] for the Size
byte[] size = { (byte)file.ReadByte(), (byte)file.ReadByte(),
(byte)file.ReadByte(), (byte)file.ReadByte()};
bmpHeader.Size = FormUint4(size);
//current position is at Byte 6 => must go to 18
file.Position = 18;
//grabs B[18,19,20,21] for the width
byte[] width = { (byte)file.ReadByte(), (byte)file.ReadByte(),
(byte)file.ReadByte(), (byte)file.ReadByte()};
bmpHeader.Width = FormUint4(width);
//grabs B[22,23,24,25] for the height
byte[] height = { (byte)file.ReadByte(), (byte)file.ReadByte(),
(byte)file.ReadByte(), (byte)file.ReadByte()};
bmpHeader.Height = FormUint4(height);
//current position is at Byte 26 => must go to 28
file.Position = 28;
//grabs B[28,29] for the BitCount
byte[] bitCount = { (byte)file.ReadByte(), (byte)file.ReadByte()};
bmpHeader.BitCount = FormUint2(bitCount);
//current position is at Byte 30 => must go to 54
file.Position = 54;
//craete the Color[] and copy it over to the bmpHeader
BuildPixels(ref bmpHeader.Pixels, ref file, bmpHeader.BitCount, (int) bmpHeader.Width, (int) bmpHeader.Height);
}
private static uint FormUint4(byte[] bytes)
{
//takes a byte array of length 4, and converts it into a uint
//this is use for getting the Size, Width, and Height of the BMP image
return (uint)(bytes[0] +
(bytes[1] * 256) +
(bytes[2] * 256 * 256) +
(bytes[3] * 256 * 256 * 256));
}
private static uint FormUint2(byte[] bytes)
{
//takes a byte array of length 2, and converts it into a uint
//this is use for getting the BitCount
return (uint)((bytes[0] +
(bytes[1] * 256)));
}
private static void BuildPixels(ref Color[] pixels, ref Stream file, uint bitCount, int pixelWidth, int pixelHeight)
{
int size = (int)(pixelWidth * pixelHeight);
int pixelPosition = 0;
pixels = new Color[size];
switch (bitCount)
{
case 1:
{
#region 1 Byte = 8 Pixels
//padding with 0s up to a 32b boundary (This can be up to 31 zeros/pixels!)
//every 1B = 8 pixel
//every Pixel is either white or black
//each pixel is 3B, but may not equal rowWidth (padding)
//to solve problem, rowWidth % 3 => padding
//each byte contains 8 bits => 8 pixels
while (file.Position < file.Length &&
pixelPosition < pixels.Length)
{
byte bits = (byte)file.ReadByte();
byte[] pVal = new byte[8];
pVal[0] = (byte)((bits << 0) >> 7);
pVal[1] = (byte)((bits << 1) >> 7);
pVal[2] = (byte)((bits << 2) >> 7);
pVal[3] = (byte)((bits << 3) >> 7);
pVal[4] = (byte)((bits << 4) >> 7);
pVal[5] = (byte)((bits << 5) >> 7);
pVal[6] = (byte)((bits << 6) >> 7);
pVal[7] = (byte)((bits << 7) >> 7);
//values for all of the pVals should be 1 or 0
for (int i = 0; i < pVal.Length; ++i)
{ //steps the pixel[] ahead by 8
pixels[pixelPosition].A = 255;
if (pVal[i] == 0)
{
//hi bit is not set, 0 = Black
pixels[pixelPosition].R = 0;
pixels[pixelPosition].G = 0;
pixels[pixelPosition++].B = 0;
}
else
{
//hi bit is set, 0 = Black, 1 = White
pixels[pixelPosition].R = 255;
pixels[pixelPosition].G = 255;
pixels[pixelPosition++].B = 255;
}
}
}
break;
#endregion
}
case 4:
{
#region 1 Byte = 2 Pixels
//every byte holds 2 pixels
while (file.Position < file.Length &&
pixelPosition < pixels.Length)
{
byte bitsRGB0x2 = (byte)file.ReadByte();
byte rVal1, gVal1, bVal1 = 0;
byte rVal2, gVal2, bVal2 = 0;
//get red
rVal1 = (byte)(bitsRGB0x2 >> 7); // RGB0 ---- => R
rVal2 = (byte)((bitsRGB0x2 << 4) >> 7); //---- RGB0 => R
//get green
gVal1 = (byte)((bitsRGB0x2 << 1) >> 7); //RGB0 ---- => G
gVal2 = (byte)((bitsRGB0x2 << 5) >> 7); //---- RGB0 => G
//get blue
bVal1 = (byte)((bitsRGB0x2 << 2) >> 7); //RGB0 ---- => B
bVal2 = (byte)((bitsRGB0x2 << 6) >> 7); // ----RGB0 => B
pixels[pixelPosition].A = 255;
pixels[pixelPosition].R = rVal1;
pixels[pixelPosition].G = gVal1;
pixels[pixelPosition++].B = bVal1;
pixels[pixelPosition].A = 255;
pixels[pixelPosition].R = rVal2;
pixels[pixelPosition].G = gVal2;
pixels[pixelPosition++].B = bVal2;
}
break;
#endregion
}
case 8:
{
#region 1 Byte = 1 Pixel
//every byte holds 1 pixel
//padding each line with 0s up to a 32bit boundary will result in up to 28 0s = 7 'wasted pixels'.
while (file.Position < file.Length &&
pixelPosition < pixels.Length)
{
byte bitsRGB0 = (byte)file.ReadByte();
byte rVal, gVal, bVal = 0;
//get red
rVal = (byte)(bitsRGB0 >> 6); // RRYY YYYY => RR
//get green
gVal = (byte)((bitsRGB0 << 2) >> 6); //YYGG YYYY => GG
//get blue
bVal = (byte)((bitsRGB0 << 4) >> 6); //XXXX BBXX => BB
pixels[pixelPosition].A = 255;
pixels[pixelPosition].R = rVal;
pixels[pixelPosition].G = gVal;
pixels[pixelPosition++].B = bVal;
}
break;
#endregion
}
case 16:
{
#region 2 Bytes = 1 Pixel
//every 2 bytes holds 1 pixel
//Padding each line with 0s up to a 32bit boundary will result in up to 3B of 0s = 3 'wasted pixels'.
while (file.Position < file.Length &&
pixelPosition < pixels.Length)
{
byte bitsRG = (byte)file.ReadByte();
byte bitsB0 = (byte)file.ReadByte();
byte rVal, gVal, bVal = 0;
//get red
rVal = (byte)(bitsRG >> 4); // XXXX YYYY => XXXX
//get green
gVal = (byte)((bitsRG << 4) >> 4); //XXXX YYYY => YYYY
//get blue
bVal = (byte)(bitsB0 >> 4);
pixels[pixelPosition].A = 255;
pixels[pixelPosition].R = rVal;
pixels[pixelPosition].G = gVal;
pixels[pixelPosition++].B = bVal;
}
break;
#endregion
}
case 24:
{
#region 3 Bytes = 1 Pixel
//no padding is necessary
//every 3B = 1 pixel
//every B is one color coord
//each color is a triple (R,G,B) w/ 1B each...24
//pixels = new Color[pixelData.Length / 3];
bool readBottomUp = true;
if (readBottomUp)
{
int bottomLeftJustifiedIndex = 0;
int x = bottomLeftJustifiedIndex % pixelWidth;
int y = pixelHeight - 1 - bottomLeftJustifiedIndex / pixelWidth;
pixelPosition = y * pixelWidth + x;
while (file.Position < file.Length &&
pixelPosition > -1)
{
pixels[pixelPosition].A = 255;
pixels[pixelPosition].B = (byte)file.ReadByte();
pixels[pixelPosition].G = (byte)file.ReadByte();
pixels[pixelPosition].R = (byte)file.ReadByte();
bottomLeftJustifiedIndex++;
//file.ReadByte();//R, G, B, reserved (should be 0)
x = bottomLeftJustifiedIndex % pixelWidth;
y = pixelHeight - 1 - bottomLeftJustifiedIndex / pixelWidth;
pixelPosition = y * pixelWidth + x;
}
}
else
{
while (file.Position < file.Length &&
pixelPosition < pixels.Length)
{
pixels[pixelPosition].A = 255;
pixels[pixelPosition].B = (byte)file.ReadByte();
pixels[pixelPosition].G = (byte)file.ReadByte();
pixels[pixelPosition++].R = (byte)file.ReadByte();
}
}
break;
#endregion
}
default:
break;
}
}
#endregion
#region Public Methods
/// <summary>
/// ImageData takes a fileName (string) and loads the BMP from the file.
/// </summary>
/// <param name="fileName"></param>
/// <returns>a new ImageData, containing the width, height, and data of the BMP that was loaded</returns>
public static ImageData GetPixelData(string fileName)
{
//Load the file into "byte stream"
Stream sourceStream = new MemoryStream(LoadFile(fileName));
//Check the signature to verify this is an actual .bmp image
if (!CheckSignature(ref sourceStream))
throw new ArgumentException(
String.Format("Argument Stream {0} does not contain a valid BMP file.", sourceStream));
BMPHeader bmpHeader = new BMPHeader();
ParseBytes(ref sourceStream, ref bmpHeader);
FileManager.Close(sourceStream);
return new ImageData((int)bmpHeader.Width, (int)bmpHeader.Height, bmpHeader.Pixels);
}
#endregion
#endregion
}
}
| |
using System;
using System.Linq;
using PowerLib.System.Collections;
namespace PowerLib.System
{
/// <summary>
/// .
/// </summary>
public sealed class JaggedArrayLongInfo : ArrayLongInfo
{
private int _rank = 0;
private long _length = 0;
private int[] _ranks;
private ArrayInfoNode _node;
private Accessor<int, int> _rankAccessor;
private ParamsAccessor<long, RegularArrayLongInfo> _dimArrayInfosAccessor;
private ParamsAccessor<long, RegularArrayLongInfo> _zeroBasedDimArrayInfosAccessor;
private ParamsAccessor<long[], RegularArrayLongInfo> _rankedDimArrayInfosAccessor;
private ParamsAccessor<long[], RegularArrayLongInfo> _zeroBasedRankedDimArrayInfosAccessor;
#region Constructors
public JaggedArrayLongInfo(Array array)
{
if (array == null)
throw new ArgumentNullException("array");
var ranks = new PwrList<int>();
var biases = new PwrList<int>();
var type = array.GetType();
for (; type.IsArray; type = type.GetElementType())
{
int rank = type.GetArrayRank();
ranks.Add(rank);
biases.Add(_rank);
_rank += rank;
}
_ranks = ranks.ToArray();
int depth = 0;
var arrayContexts = new PwrStack<ArrayInfoNodeContext>();
var arrayInfo = new RegularArrayLongInfo(array.GetRegularArrayLongDimensions());
var arrayIndex = new ArrayLongIndex(arrayInfo);
var node = new ArrayInfoNode(arrayInfo, _length, depth == _ranks.Length - 1);
descent:
while (depth < _ranks.Length - 1)
{
if (array.Length > 0)
for (; arrayIndex.Carry == 0 && arrayIndex.GetValue<Array>(array) == null; arrayIndex++) ;
if (arrayIndex.Carry != 0 || array.Length == 0)
break;
depth++;
arrayContexts.Push(new ArrayInfoNodeContext(node, array, arrayIndex));
array = arrayIndex.GetValue<Array>(array);
arrayInfo = new RegularArrayLongInfo(array.GetRegularArrayLongDimensions());
arrayIndex.SetValue<ArrayInfoNode>(node.Nodes, new ArrayInfoNode(arrayInfo, _length, depth == _ranks.Length - 1));
if (depth == _ranks.Length - 1)
_length += array.Length;
else
{
node = arrayIndex.GetValue<ArrayInfoNode>(node.Nodes);
arrayIndex = new ArrayLongIndex(arrayInfo);
}
}
ascent:
if (depth != 0)
{
var nodeContext = arrayContexts.Pop();
array = nodeContext.Array;
node = nodeContext.Node;
arrayIndex = nodeContext.Index;
depth--;
if (arrayIndex.IsMax)
goto ascent;
else
{
arrayIndex++;
goto descent;
}
}
_node = node;
}
public JaggedArrayLongInfo(int[] ranks, Func<int, long[], long[][], long[]> lensGetter, long[] flatIndices, long[][] dimIndices)
: this(ranks, lensGetter != null ?
(depth, rankedFlatIndices, rankedDimindices) => lensGetter(depth, rankedFlatIndices, rankedDimindices).Select<long, ArrayLongDimension>(length => new ArrayLongDimension(length)).ToArray() :
default(Func<int, long[], long[][], ArrayLongDimension[]>), flatIndices, dimIndices)
{
}
public JaggedArrayLongInfo(int[] ranks, Func<int, long[], long[][], ArrayLongDimension[]> dimsGetter, long[] flatIndices, long[][] dimIndices)
{
if (ranks == null)
throw new ArgumentNullException("ranks");
if (dimsGetter == null)
throw new ArgumentNullException("dimsGetter");
int rank = 0;
for (int i = 0; i < ranks.Length; i++)
{
if (ranks[i] < 0)
throw new ArgumentCollectionElementException("ranks", ArrayResources.Default.Strings[ArrayMessage.ArrayElementOutOfRange], i);
if (dimIndices != null)
{
if (dimIndices[i] == null)
throw new ArgumentCollectionElementException("rankedIndices", "Argument has NULL value.", i);
if (dimIndices[i].Length != ranks[i])
throw new ArgumentException(ArrayResources.Default.Strings[ArrayMessage.InvalidArrayLength], "rankedIndices");
}
rank += ranks[i];
}
if (flatIndices != null && flatIndices.Length != ranks.Length)
throw new ArgumentException(ArrayResources.Default.Strings[ArrayMessage.InvalidArrayLength], "flatIndices");
_rank = rank;
_ranks = (int[])ranks.Clone();
int depth = 0;
var arrayContexts = new PwrStack<ArrayInfoNodeContext>();
var arrayInfo = new RegularArrayLongInfo(dimsGetter(depth, flatIndices, dimIndices));
var arrayIndex = new ArrayLongIndex(arrayInfo);
var node = new ArrayInfoNode(arrayInfo, _length, depth == _ranks.Length - 1);
descent:
while (depth < _ranks.Length - 1)
{
ArrayLongDimension[] arrayDims = null;
if (arrayInfo.Length > 0)
for (flatIndices[depth] = arrayIndex.FlatIndex, arrayIndex.GetDimIndices(dimIndices[depth]);
arrayIndex.Carry == 0 && (arrayDims = dimsGetter(depth + 1, flatIndices, dimIndices)) == null;
arrayIndex++, flatIndices[depth] = arrayIndex.FlatIndex, arrayIndex.GetDimIndices(dimIndices[depth])) ;
if (arrayIndex.Carry != 0 || arrayInfo.Length == 0)
break;
depth++;
arrayContexts.Push(new ArrayInfoNodeContext(node, null, arrayIndex));
arrayInfo = new RegularArrayLongInfo(arrayDims);
arrayIndex.SetValue<ArrayInfoNode>(node.Nodes, new ArrayInfoNode(arrayInfo, _length, depth == _ranks.Length - 1));
if (depth == _ranks.Length - 1)
_length += arrayInfo.Length;
else
{
node = arrayIndex.GetValue<ArrayInfoNode>(node.Nodes);
arrayIndex = new ArrayLongIndex(arrayInfo);
}
}
ascent:
if (depth != 0)
{
var nodeContext = arrayContexts.Pop();
node = nodeContext.Node;
arrayIndex = nodeContext.Index;
depth--;
if (arrayIndex.IsMax)
goto ascent;
else
{
arrayIndex++;
goto descent;
}
}
_node = node;
}
#endregion
#region Instance properties
public override int Rank
{
get
{
return _rank;
}
}
public override long Length
{
get
{
return _length;
}
}
public int Depths
{
get
{
return _ranks.Length;
}
}
public Accessor<int, int> Ranks
{
get
{
if (_rankAccessor == null)
_rankAccessor = new Accessor<int, int>(dim => GetRank(dim));
return null;
}
}
public ParamsAccessor<long, RegularArrayLongInfo> DimArrayInfos
{
get
{
if (_dimArrayInfosAccessor == null)
_dimArrayInfosAccessor = new ParamsAccessor<long, RegularArrayLongInfo>(dimIndices => GetDimArrayInfo(false, dimIndices));
return _dimArrayInfosAccessor;
}
}
public ParamsAccessor<long, RegularArrayLongInfo> ZeroBasedDimArrayInfos
{
get
{
if (_zeroBasedDimArrayInfosAccessor == null)
_zeroBasedDimArrayInfosAccessor = new ParamsAccessor<long, RegularArrayLongInfo>(dimIndices => GetDimArrayInfo(true, dimIndices));
return _zeroBasedDimArrayInfosAccessor;
}
}
public ParamsAccessor<long[], RegularArrayLongInfo> RankedDimArrayInfos
{
get
{
if (_rankedDimArrayInfosAccessor == null)
_rankedDimArrayInfosAccessor = new ParamsAccessor<long[], RegularArrayLongInfo>(dimIndices => GetDimArrayInfo(false, dimIndices));
return _rankedDimArrayInfosAccessor;
}
}
public ParamsAccessor<long[], RegularArrayLongInfo> ZeroBasedRankedDimArrayInfos
{
get
{
if (_zeroBasedRankedDimArrayInfosAccessor == null)
_zeroBasedRankedDimArrayInfosAccessor = new ParamsAccessor<long[], RegularArrayLongInfo>(dimIndices => GetDimArrayInfo(true, dimIndices));
return _zeroBasedRankedDimArrayInfosAccessor;
}
}
#endregion
#region Instance methods
#region Internal methods
private long CalcFlatIndexCore(bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < _ranks.Length - 1 && node != null; i++)
node = node.ArrayInfo.GetValue<ArrayInfoNode>(node.Nodes, false, zeroBased, indices[i]);
//
if (node == null)
throw new InvalidOperationException("Invalid internal array index");
//
return node.Total + node.ArrayInfo.CalcFlatIndex(zeroBased, indices[_ranks.Length - 1]);
}
private void CalcDimIndicesCore(long flatIndex, bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < _ranks.Length - 1 && node != null; i++)
{
//
ArrayLongIndex lowerIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
lowerIndex.SetMin();
ArrayInfoNode lowerNode = null;
for (; lowerIndex.Carry == 0 && (lowerNode = lowerIndex.GetValue<ArrayInfoNode>(node.Nodes)) == null; lowerIndex++) ;
//
ArrayLongIndex upperIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
upperIndex.SetMax();
ArrayInfoNode upperNode = null;
for (; upperIndex.Carry == 0 && (upperNode = upperIndex.GetValue<ArrayInfoNode>(node.Nodes)) == null; upperIndex--) ;
//
if (lowerNode == null && upperNode == null)
{
node = null;
continue;
}
//
while (flatIndex < upperNode.Total && upperIndex.FlatIndex - lowerIndex.FlatIndex > 1)
{
ArrayLongIndex middleIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased, FlatIndex = (lowerIndex.FlatIndex + upperIndex.FlatIndex) / 2 };
ArrayInfoNode middleNode = middleIndex.GetValue<ArrayInfoNode>(node.Nodes);
if (middleNode == null)
{
ArrayLongIndex searchIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
searchIndex.SetFrom(middleIndex);
for (searchIndex--; searchIndex.FlatIndex > lowerIndex.FlatIndex && (middleNode = searchIndex.GetValue<ArrayInfoNode>(node.Nodes)) == null; searchIndex--) ;
if (middleNode == null)
{
searchIndex.SetFrom(middleIndex);
for (searchIndex++; searchIndex.FlatIndex < upperIndex.FlatIndex && (middleNode = searchIndex.GetValue<ArrayInfoNode>(node.Nodes)) == null; searchIndex++) ;
if (middleNode == null)
break;
}
middleIndex.SetFrom(searchIndex);
}
//
if (flatIndex < middleNode.Total)
{
upperIndex.SetFrom(middleIndex);
upperIndex--;
upperNode = upperIndex.GetValue<ArrayInfoNode>(node.Nodes);
}
else
{
lowerIndex.SetFrom(middleIndex);
lowerNode = middleNode;
}
}
//
for (int j = 0; j < _ranks[i]; j++)
indices[i][j] = flatIndex >= upperNode.Total ? upperIndex.DimIndices[j] : lowerIndex.DimIndices[j];
node = flatIndex >= upperNode.Total ? upperNode : lowerNode;
}
//
if (node == null)
throw new InvalidOperationException("Invalid internal array index");
//
ArrayLongIndex arrayIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
arrayIndex.FlatIndex = flatIndex - node.Total;
for (int j = 0; j < _ranks[_ranks.Length - 1]; j++)
indices[_ranks.Length - 1][j] = arrayIndex.DimIndices[j];
}
private void FirstDimIndicesCore(bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < _ranks.Length - 1 && node != null; i++)
{
ArrayLongIndex thisIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
thisIndex.SetMin();
ArrayInfoNode thisNode = null;
for (; thisIndex.Carry == 0 && (thisNode = thisIndex.GetValue<ArrayInfoNode>(node.Nodes)) == null; thisIndex++) ;
if (thisIndex.Carry != 0)
node = null;
else
{
//
ArrayLongIndex nextIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
nextIndex.SetFrom(thisIndex);
ArrayInfoNode nextNode = null;
for (nextIndex++; nextIndex.Carry == 0; nextIndex++)
{
nextNode = nextIndex.GetValue<ArrayInfoNode>(node.Nodes);
if (nextNode == null)
continue;
if (nextNode.Total > thisNode.Total)
break;
thisNode = nextNode;
thisIndex.SetFrom(nextIndex);
}
//
thisIndex.GetDimIndices(indices[i]);
node = thisIndex.GetValue<ArrayInfoNode>(node.Nodes);
}
}
//
if (node == null)
throw new InvalidOperationException("Invalid internal array index");
//
ArrayLongIndex arrayIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
arrayIndex.SetMin();
arrayIndex.GetDimIndices(indices[_ranks.Length - 1]);
}
private void LastDimIndicesCore(bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < _ranks.Length - 1 && node != null; i++)
{
ArrayLongIndex thisIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
thisIndex.SetMax();
ArrayInfoNode thisNode = thisIndex.GetValue<ArrayInfoNode>(node.Nodes);
for (; thisIndex.Carry == 0; thisIndex--)
{
thisNode = thisIndex.GetValue<ArrayInfoNode>(node.Nodes);
if (thisNode == null)
continue;
if (thisNode.Total < _length)
break;
}
if (thisIndex.Carry != 0)
node = null;
{
//
thisIndex.GetDimIndices(indices[i]);
node = thisIndex.GetValue<ArrayInfoNode>(node.Nodes);
}
}
//
if (node == null)
throw new InvalidOperationException("Invalid internal array index");
//
ArrayLongIndex arrayIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
arrayIndex.SetMax();
arrayIndex.GetDimIndices(indices[_ranks.Length - 1]);
}
private bool NextDimIndicesCore(bool zeroBased, long[][] indices)
{
PwrStack<ArrayInfoNodeContext> arrayContexts = new PwrStack<ArrayInfoNodeContext>();
ArrayInfoNode node = _node;
ArrayLongIndex arrayIndex = null;
int depth = 0;
for (; depth < _ranks.Length - 1 && node != null; depth++)
{
arrayIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
arrayIndex.SetDimIndices(indices[depth]);
ArrayInfoNodeContext nodeContext = new ArrayInfoNodeContext(node, null, arrayIndex);
node = arrayIndex.GetValue<ArrayInfoNode>(node.Nodes);
if (node != null)
arrayContexts.Push(nodeContext);
}
//
if (node == null)
throw new InvalidOperationException("Invalid internal array index");
if (!node.ArrayInfo.IncDimIndices(zeroBased, indices[_ranks.Length - 1]))
return false;
long total = node.Total + node.ArrayInfo.Length;
if (total == _length)
return true;
//
descent:
while (depth < _ranks.Length - 1)
{
ArrayInfoNode n = null;
for (; arrayIndex.Carry == 0 && (n = arrayIndex.GetValue<ArrayInfoNode>(node.Nodes)) == null; arrayIndex++) ;
if (n == null)
break;
arrayContexts.Push(new ArrayInfoNodeContext(node, null, arrayIndex));
depth++;
node = n;
if (depth < _ranks.Length - 1)
{
arrayIndex = new ArrayLongIndex(node.ArrayInfo);
arrayIndex.SetMin();
}
else if (node.Total == total && node.ArrayInfo.Length > 0)
{
node.ArrayInfo.GetMinDimIndices(zeroBased, indices[_ranks.Length - 1]);
while (arrayContexts.Count > 0)
{
ArrayInfoNodeContext nodeContext = arrayContexts.Pop();
nodeContext.Index.GetDimIndices(indices[arrayContexts.Count]);
}
return false;
}
}
ascent:
if (depth != 0)
{
ArrayInfoNodeContext nodeContext = arrayContexts.Pop();
node = nodeContext.Node;
arrayIndex = nodeContext.Index;
depth--;
if (arrayIndex.IsMax)
goto ascent;
else
{
arrayIndex++;
goto descent;
}
}
//
return false;
}
private bool PrevDimIndicesCore(bool zeroBased, long[][] indices)
{
PwrStack<ArrayInfoNodeContext> arrayContexts = new PwrStack<ArrayInfoNodeContext>();
ArrayInfoNode node = _node;
ArrayLongIndex arrayIndex = null;
int depth = 0;
for (; depth < _ranks.Length - 1 && node != null; depth++)
{
arrayIndex = new ArrayLongIndex(node.ArrayInfo) { ZeroBased = zeroBased };
arrayIndex.SetDimIndices(indices[depth]);
ArrayInfoNodeContext nodeContext = new ArrayInfoNodeContext(node, null, arrayIndex);
node = arrayIndex.GetValue<ArrayInfoNode>(node.Nodes);
if (node != null)
arrayContexts.Push(nodeContext);
}
//
if (node == null)
throw new InvalidOperationException("Invalid internal array index");
if (!node.ArrayInfo.DecDimIndices(zeroBased, indices[_ranks.Length - 1]))
return false;
if (node.Total == 0)
return true;
long total = node.Total;
//
descent:
while (depth < _ranks.Length - 1)
{
ArrayInfoNode n = null;
for (; arrayIndex.Carry == 0 && (n = arrayIndex.GetValue<ArrayInfoNode>(node.Nodes)) == null; arrayIndex--) ;
if (n == null)
break;
arrayContexts.Push(new ArrayInfoNodeContext(node, null, arrayIndex));
depth++;
node = n;
if (depth < _ranks.Length - 1)
{
arrayIndex = new ArrayLongIndex(node.ArrayInfo);
arrayIndex.SetMax();
}
else if (node.Total == (total - node.ArrayInfo.Length) && node.ArrayInfo.Length > 0)
{
node.ArrayInfo.GetMaxDimIndices(zeroBased, indices[_ranks.Length - 1]);
while (arrayContexts.Count > 0)
{
ArrayInfoNodeContext nodeContext = arrayContexts.Pop();
nodeContext.Index.GetDimIndices(indices[arrayContexts.Count]);
}
return false;
}
}
ascent:
if (depth != 0)
{
ArrayInfoNodeContext nodeContext = arrayContexts.Pop();
node = nodeContext.Node;
arrayIndex = nodeContext.Index;
depth--;
if (arrayIndex.IsMin)
goto ascent;
else
{
arrayIndex--;
goto descent;
}
}
//
return false;
}
private object GetValueCore(Array array, bool asRanges, bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < _ranks.Length - 1 && node != null && array != null; i++)
{
array = node.ArrayInfo.GetValue<Array>(array, asRanges, zeroBased, indices[i]);
node = node.ArrayInfo.GetValue<ArrayInfoNode>(node.Nodes, false, zeroBased, indices[i]);
}
//
if (node == null || array == null)
throw new InvalidOperationException("Invalid internal array index");
//
return node.ArrayInfo.GetValue(array, asRanges, zeroBased, indices[_ranks.Length - 1]);
}
private void SetValueCore(Array array, object value, bool asRanges, bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < _ranks.Length - 1 && node != null && array != null; i++)
{
array = node.ArrayInfo.GetValue<Array>(array, asRanges, zeroBased, indices[i]);
node = node.ArrayInfo.GetValue<ArrayInfoNode>(node.Nodes, false, zeroBased, indices[i]);
}
//
if (node == null || array == null)
throw new InvalidOperationException("Invalid internal array index");
//
node.ArrayInfo.SetValue(array, value, asRanges, zeroBased, indices[_ranks.Length - 1]);
}
private T GetValueCore<T>(Array array, bool asRanges, bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < _ranks.Length - 1 && node != null && array != null; i++)
{
array = node.ArrayInfo.GetValue<Array>(array, asRanges, zeroBased, indices[i]);
node = node.ArrayInfo.GetValue<ArrayInfoNode>(node.Nodes, false, zeroBased, indices[i]);
}
//
if (node == null || array == null)
throw new InvalidOperationException("Invalid internal array index");
//
return node.ArrayInfo.GetValue<T>(array, asRanges, zeroBased, indices[_ranks.Length - 1]);
}
private void SetValueCore<T>(Array array, T value, bool asRanges, bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < _ranks.Length - 1 && node != null && array != null; i++)
{
array = node.ArrayInfo.GetValue<Array>(array, asRanges, zeroBased, indices[i]);
node = node.ArrayInfo.GetValue<ArrayInfoNode>(node.Nodes, false, zeroBased, indices[i]);
}
//
if (node == null || array == null)
throw new InvalidOperationException("Invalid internal array index");
//
node.ArrayInfo.SetValue<T>(array, value, asRanges, zeroBased, indices[_ranks.Length - 1]);
}
private RegularArrayLongInfo GetDimArrayInfoCore(bool zeroBased, long[][] indices)
{
ArrayInfoNode node = _node;
for (int i = 0; i < indices.Length && node != null; i++)
node = node.ArrayInfo.GetValue<ArrayInfoNode>(node.Nodes, false, zeroBased, indices[i]);
//
if (node == null)
throw new InvalidOperationException("Invalid internal array index");
//
return node.ArrayInfo;
}
#endregion
#region Public methods
public int GetRank(int depth)
{
if (depth < 0 || depth >= _ranks.Length)
throw new ArgumentOutOfRangeException("depth");
//
return _ranks[depth];
}
public override Array CreateArray(Type elementType)
{
if (elementType == null)
throw new ArgumentNullException("elementType");
//
Type[] types = new Type[_ranks.Length];
types[_ranks.Length - 1] = elementType;
for (int i = _ranks.Length - 1; i > 0; i--)
types[i - 1] = _ranks[i] == 1 ? types[i].MakeArrayType() : types[i].MakeArrayType(_ranks[i]);
//
int depth = 0;
PwrStack<ArrayInfoNodeContext> arrayContexts = new PwrStack<ArrayInfoNodeContext>();
ArrayInfoNode node = _node;
Array array = node.ArrayInfo.CreateArray(types[depth]);
ArrayLongIndex arrayIndex = new ArrayLongIndex(node.ArrayInfo);
descent:
while (depth < _ranks.Length - 1)
{
if (array.Length == 0)
break;
arrayContexts.Push(new ArrayInfoNodeContext(node, array, arrayIndex));
depth++;
node = arrayIndex.GetValue<ArrayInfoNode>(node.Nodes);
Array a = node.ArrayInfo.CreateArray(types[depth]);
arrayIndex.SetValue<Array>(array, a);
array = a;
if (depth < _ranks.Length - 1)
arrayIndex = new ArrayLongIndex(node.ArrayInfo);
}
ascent:
if (depth != 0)
{
ArrayInfoNodeContext nodeContext = arrayContexts.Pop();
array = nodeContext.Array;
node = nodeContext.Node;
arrayIndex = nodeContext.Index;
depth--;
if (arrayIndex.IsMax)
goto ascent;
else
{
arrayIndex++;
goto descent;
}
}
//
return array;
}
public override object GetValue(Array array, bool asRanges, bool zeroBased, params long[] dimIndices)
{
if (array == null)
throw new ArgumentNullException("array");
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array length", "indices");
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices, j, indices[i], 0, _ranks[i]);
}
return GetValueCore(array, asRanges, zeroBased, indices);
}
public override void SetValue(Array array, object value, bool asRanges, bool zeroBased, params long[] dimIndices)
{
if (array == null)
throw new ArgumentNullException("array");
if (!array.GetJaggedArrayElementType().IsValueAssignable(value))
throw new ArgumentException("Inassignable value", "value");
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array length", "indices");
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices, j, indices[i], 0, _ranks[i]);
}
SetValueCore(array, value, asRanges, zeroBased, indices);
}
public object GetValue(Array array, long[][] dimIndices)
{
return GetValue(array, false, false, dimIndices);
}
public object GetValue(Array array, bool asRanges, bool zeroBased, long[][] dimIndices)
{
if (array == null)
throw new ArgumentNullException("array");
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array length", "indices");
else
for (int i = 0; i < dimIndices.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("dimIndices", "Value cannot be null", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("dimIndices", "Invalid array length", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
return GetValueCore(array, asRanges, zeroBased, dimIndices);
}
public void SetValue(Array array, object value, long[][] dimIndices)
{
SetValue(array, value, false, false, dimIndices);
}
public void SetValue(Array array, object value, bool asRanges, bool zeroBased, long[][] dimIndices)
{
if (array == null)
throw new ArgumentNullException("array");
if (!array.GetJaggedArrayElementType().IsValueAssignable(value))
throw new ArgumentException("Inassignable value", "value");
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array length", "indices");
else
for (int i = 0; i < dimIndices.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("dimIndices", "Nulvalue ", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("dimIndices", "Invalid array length", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
SetValueCore(array, value, asRanges, zeroBased, dimIndices);
}
public override T GetValue<T>(Array array, bool asRanges, bool zeroBased, params long[] dimIndices)
{
if (array == null)
throw new ArgumentNullException("array");
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array length", "indices");
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices, j, indices[i], 0, _ranks[i]);
}
return GetValueCore<T>(array, asRanges, zeroBased, indices);
}
public override void SetValue<T>(Array array, T value, bool asRanges, bool zeroBased, params long[] dimIndices)
{
if (array == null)
throw new ArgumentNullException("array");
if (!array.GetJaggedArrayElementType().IsValueAssignable(value))
throw new ArgumentException("Inassignable value", "value");
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array length", "indices");
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices, j, indices[i], 0, _ranks[i]);
}
SetValueCore<T>(array, value, asRanges, zeroBased, indices);
}
public T GetValue<T>(Array array, long[][] dimIndices)
{
return GetValue<T>(array, false, false, dimIndices);
}
public T GetValue<T>(Array array, bool asRanges, bool zeroBased, long[][] dimIndices)
{
if (array == null)
throw new ArgumentNullException("array");
else if (typeof(T).IsAssignableFrom(array.GetJaggedArrayElementType()))
throw new ArgumentNullException("Inconsistent array element type");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array length", "indices");
else
for (int i = 0; i < dimIndices.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("dimIndices", "Value cannot be null", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("dimIndices", "Invalid array length", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
return GetValueCore<T>(array, asRanges, zeroBased, dimIndices);
}
public void SetValue<T>(Array array, T value, long[][] dimIndices)
{
SetValue(array, value, false, false, dimIndices);
}
public void SetValue<T>(Array array, T value, bool asRanges, bool zeroBased, long[][] dimIndices)
{
if (array == null)
throw new ArgumentNullException("array");
else if (array.GetJaggedArrayElementType().IsAssignableFrom(value != null ? value.GetType() : typeof(T)))
throw new ArgumentNullException("Inconsistent array element type");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array length", "indices");
else
for (int i = 0; i < dimIndices.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("dimIndices", "Nulvalue ", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("dimIndices", "Invalid array length", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
SetValueCore(array, value, asRanges, zeroBased, dimIndices);
}
public override long CalcFlatIndex(bool zeroBased, params long[] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array length", "indices");
else if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices, j, indices[i], 0, _ranks[i]);
}
//
return CalcFlatIndexCore(zeroBased, indices);
}
public override void CalcDimIndices(long flatIndex, bool zeroBased, long[] dimIndices)
{
if (flatIndex < 0 || flatIndex >= _length)
throw new ArgumentOutOfRangeException("flatIndex");
else if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array length", "dimIndices");
else if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0; i < _ranks.Length; i++)
indices[i] = new long[_ranks[i]];
//
CalcDimIndicesCore(flatIndex, zeroBased, indices);
//
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
Array.Copy(indices[i], 0, dimIndices, j, _ranks[i]);
}
public override void GetMinDimIndices(bool zeroBased, long[] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array size", "dimIndices");
else if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
indices[i] = new long[_ranks[i]];
//
FirstDimIndicesCore(zeroBased, indices);
//
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
Array.Copy(indices[i], 0, dimIndices, j, _ranks[i]);
}
public override void GetMaxDimIndices(bool zeroBased, long[] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array size", "dimIndices");
else if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
indices[i] = new long[_ranks[i]];
//
LastDimIndicesCore(zeroBased, indices);
//
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
Array.Copy(indices[i], 0, dimIndices, j, _ranks[i]);
}
public override bool IncDimIndices(bool zeroBased, long[] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array size", "dimIndices");
else if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices, j, indices[i], 0, _ranks[i]);
}
//
bool carry = NextDimIndicesCore(zeroBased, indices);
if (carry)
FirstDimIndicesCore(zeroBased, indices);
//
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
Array.Copy(indices[i], 0, dimIndices, j, _ranks[i]);
return carry;
}
public override bool DecDimIndices(bool zeroBased, long[] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array size", "dimIndices");
else if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices, j, indices[i], 0, _ranks[i]);
}
//
bool carry = PrevDimIndicesCore(zeroBased, indices);
if (carry)
LastDimIndicesCore(zeroBased, indices);
//
for (int i = 0, j = 0; i < _ranks.Length && j < _rank; j += _ranks[i++])
Array.Copy(indices[i], 0, dimIndices, j, _ranks[i]);
return carry;
}
public long CalcFlatIndex(long[][] dimIndices)
{
return CalcFlatIndex(false, dimIndices);
}
public long CalcFlatIndex(bool zeroBased, long[][] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array length", "indices");
else
for (int i = 0; i < dimIndices.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("dimIndices", "Value cannot be null", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("dimIndices", "Invalid array length", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
return CalcFlatIndexCore(zeroBased, dimIndices);
}
public void CalcDimIndices(long flatIndex, long[][] dimIndices)
{
CalcDimIndices(flatIndex, false, dimIndices);
}
public void CalcDimIndices(long flatIndex, bool zeroBased, long[][] dimIndices)
{
if (flatIndex < 0 || flatIndex >= _length)
throw new ArgumentOutOfRangeException("flatIndex");
else if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _rank)
throw new ArgumentException("Invalid array length", "dimIndices");
else
for (int i = 0; i < _ranks.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("Value is null", "dimIndices", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("Invalid array size", "dimIndices", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0; i < _ranks.Length; i++)
indices[i] = new long[_ranks[i]];
//
CalcDimIndicesCore(flatIndex, zeroBased, indices);
//
for (int i = 0; i < _ranks.Length; i++)
Array.Copy(indices[i], 0, dimIndices[i], 0, _ranks[i]);
}
public void GetMinDimIndices(long[][] dimIndices)
{
GetMinDimIndices(false, dimIndices);
}
public void GetMinDimIndices(bool zeroBased, long[][] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array size", "dimIndices");
else
for (int i = 0; i < _ranks.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("Value is null", "dimIndices", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("Invalid array size", "dimIndices", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0; i < _ranks.Length; i++)
indices[i] = new long[_ranks[i]];
//
FirstDimIndicesCore(zeroBased, indices);
//
for (int i = 0; i < _ranks.Length; i++)
Array.Copy(indices[i], 0, dimIndices[i], 0, _ranks[i]);
}
public void GetMaxDimIndices(long[][] dimIndices)
{
GetMaxDimIndices(false, dimIndices);
}
public void GetMaxDimIndices(bool zeroBased, long[][] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array size", "dimIndices");
else
for (int i = 0; i < _ranks.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("Value is null", "dimIndices", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("Invalid array size", "dimIndices", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0; i < _ranks.Length; i++)
indices[i] = new long[_ranks[i]];
//
LastDimIndicesCore(zeroBased, indices);
//
for (int i = 0; i < _ranks.Length; i++)
Array.Copy(indices[i], 0, dimIndices[i], 0, _ranks[i]);
}
public bool IncDimIndices(long[][] dimIndices)
{
return IncDimIndices(false, dimIndices);
}
public bool IncDimIndices(bool zeroBased, long[][] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array size", "dimIndices");
else
for (int i = 0; i < _ranks.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("Value is null", "dimIndices", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("Invalid array size", "dimIndices", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0; i < _ranks.Length; i++)
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices[i], 0, indices[i], 0, _ranks.Length);
}
//
bool carry = NextDimIndicesCore(zeroBased, indices);
if (carry)
FirstDimIndicesCore(zeroBased, indices);
//
for (int i = 0; i < _ranks.Length; i++)
Array.Copy(indices[i], 0, dimIndices[i], 0, _ranks[i]);
return carry;
}
public bool DecDimIndices(long[][] dimIndices)
{
return DecDimIndices(false, dimIndices);
}
public bool DecDimIndices(bool zeroBased, long[][] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length != _ranks.Length)
throw new ArgumentException("Invalid array size", "dimIndices");
else
for (int i = 0; i < _ranks.Length; i++)
if (dimIndices[i] == null)
throw new ArgumentRegularArrayLongElementException("Value is null", "dimIndices", i);
else if (dimIndices[i].Length != _ranks[i])
throw new ArgumentRegularArrayLongElementException("Invalid array size", "dimIndices", i);
if (_length == 0)
throw new InvalidOperationException("Array has zero length");
//
long[][] indices = new long[_ranks.Length][];
for (int i = 0; i < _ranks.Length; i++)
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices[i], 0, indices[i], 0, _ranks.Length);
}
//
bool carry = PrevDimIndicesCore(zeroBased, indices);
if (carry)
LastDimIndicesCore(zeroBased, indices);
//
for (int i = 0; i < _ranks.Length; i++)
Array.Copy(indices[i], 0, dimIndices[i], 0, _ranks[i]);
return carry;
}
public RegularArrayLongInfo GetDimArrayInfo(bool zeroBased, params long[] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length < 1 || dimIndices.Length > _rank - _ranks[_ranks.Length - 1])
throw new ArgumentException("Invalid array length", "dimIndices");
int length = dimIndices.Length;
int depth = 0;
for (; depth < _ranks.Length - 1 && length >= _ranks[depth]; length -= _ranks[depth], depth++) ;
if (length != 0)
throw new ArgumentException("Invalid array length", "dimIndices");
long[][] indices = new long[depth][];
for (int i = 0, j = 0; i < depth && j < dimIndices.Length; j += _ranks[i++])
{
indices[i] = new long[_ranks[i]];
Array.Copy(dimIndices, j, indices[i], 0, _ranks[i]);
}
return GetDimArrayInfoCore(zeroBased, indices);
}
public RegularArrayLongInfo GetDimArrayInfo(bool zeroBased, params long[][] dimIndices)
{
if (dimIndices == null)
throw new ArgumentNullException("dimIndices");
else if (dimIndices.Length < 1 || dimIndices.Length > _ranks.Length - 1)
throw new ArgumentException("Invalid array length", "dimIndices");
else
for (int j = 0; j < dimIndices.Length; j++)
if (dimIndices[j] == null)
throw new ArgumentRegularArrayLongElementException("Array is null", "dimIndices", j);
else if (dimIndices[j].Length != _ranks[j])
throw new ArgumentRegularArrayLongElementException("Invalid array length", "dimIndices", j);
return GetDimArrayInfoCore(zeroBased, dimIndices);
}
#endregion
#endregion
#region Embedded types
class ArrayInfoNodeContext
{
public ArrayInfoNodeContext(ArrayInfoNode node, Array array, ArrayLongIndex index)
{
Node = node;
Array = array;
Index = index;
}
public ArrayInfoNode Node
{
get;
private set;
}
public Array Array
{
get;
private set;
}
public ArrayLongIndex Index
{
get;
private set;
}
}
class ArrayInfoNode
{
public ArrayInfoNode(RegularArrayLongInfo arrayInfo, long total, bool elementary)
{
ArrayInfo = arrayInfo;
Nodes = !elementary ? arrayInfo.CreateArray(typeof(ArrayInfoNode)) : null;
Total = total;
}
public RegularArrayLongInfo ArrayInfo
{
get;
private set;
}
public Array Nodes
{
get;
private set;
}
public long Total
{
get;
private set;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.IO;
using Microsoft.Kinect;
using Microsoft.Kinect.Toolkit;
using Microsoft.Kinect.Toolkit.Interaction;
namespace FUKinectTool
{
/// <summary>
/// Some Regularly Used Functions in Kinect Programming. Use only one instance for all functions.
/// TakeColorPicture()
/// TakeDepthPicture()
/// GetKinectColorCameraFrame()
/// GetKinectColorCameraFrame( ColorImageFrame colorImageFrame )
/// GetKinectDepthCameraFrame( DepthImageFrame depthImageFrame )
/// </summary>
public class FUKinectHelper
{
#region Kinect Camera Methods
/// <summary>
/// Bitmap that will hold color information
/// </summary>
private WriteableBitmap _colorBitmap;
/// <summary>
/// Bitmap that will hold depth information
/// </summary>
private WriteableBitmap _depthBitmap;
/// <summary>
/// Takes image from the color camera. Only available If you're getting the color image frame from FUKinectHelper
/// </summary>
public bool TakeColorPicture()
{
if (_colorBitmap == null)
return false;
// create a png bitmap encoder which knows how to save a .png file
BitmapEncoder encoder = new PngBitmapEncoder();
// create frame from the writable bitmap and add to encoder
encoder.Frames.Add( BitmapFrame.Create( _colorBitmap ) );
string time = System.DateTime.Now.ToString( "hh'-'mm'-'ss", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat );
string myPhotos = Environment.GetFolderPath( Environment.SpecialFolder.MyPictures );
string path = Path.Combine( myPhotos, "KinectColorSnapshot-" + time + ".png" );
// write the new file to disk
try
{
using (FileStream fs = new FileStream( path, FileMode.Create ))
{
encoder.Save( fs );
}
}
catch
{
//TODO: Find a way to show error message
return false;
}
return true;
}
/// <summary>
/// Takes image from the depth camera. Only available If you're getting the depth image frame from FUKinectHelper
/// </summary>
public bool TakeDepthPicture()
{
if (_depthBitmap == null)
return false;
// create a png bitmap encoder which knows how to save a .png file
BitmapEncoder encoder = new PngBitmapEncoder();
// create frame from the writable bitmap and add to encoder
encoder.Frames.Add( BitmapFrame.Create( _depthBitmap ) );
string time = System.DateTime.Now.ToString( "hh'-'mm'-'ss", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat );
string myPhotos = Environment.GetFolderPath( Environment.SpecialFolder.MyPictures );
string path = Path.Combine( myPhotos, "KinectDepthSnapshot-" + time + ".png" );
// write the new file to disk
try
{
using (FileStream fs = new FileStream( path, FileMode.Create ))
{
encoder.Save( fs );
}
}
catch
{
//TODO: Find a way to show error message
return false;
}
return true;
}
/// <summary>
/// Takes ColorImageFrame and returns a BitmapSource containing Kinect Color Camera Frame
/// </summary>
/// <param name="e">ColorImageFrame</param>
byte[] _colorPixels = null;
public BitmapSource GetKinectColorCameraFrame( ColorImageFrame colorImageFrame )
{
if (colorImageFrame == null)
return null;
if (_colorBitmap == null)
_colorBitmap = new WriteableBitmap( colorImageFrame.Width, colorImageFrame.Height, 96.0, 96.0, System.Windows.Media.PixelFormats.Bgr32, null );
if (_colorPixels == null)
_colorPixels = new byte[colorImageFrame.PixelDataLength];
colorImageFrame.CopyPixelDataTo( _colorPixels );
// Write the pixel data into our bitmap
_colorBitmap.WritePixels( new System.Windows.Int32Rect( 0, 0, _colorBitmap.PixelWidth, _colorBitmap.PixelHeight ), _colorPixels,
_colorBitmap.PixelWidth * sizeof( int ), 0 );
return _colorBitmap;
}
/// <summary>
/// Takes DepthImageFrame and returns a BitmapSource containing Kinect Depth Camera Frame
/// </summary>
/// <param name="e">DepthImageFrame</param>
byte[] _depthPixels;
public WriteableBitmap GetKinectDepthCameraFrame( DepthImageFrame depthImageFrame )
{
if (depthImageFrame == null)
return null;
if (_depthBitmap == null)
_depthBitmap = new WriteableBitmap( depthImageFrame.Width, depthImageFrame.Height, 96, 96, System.Windows.Media.PixelFormats.Bgr32, null );
_depthPixels = GenerateColoredPixels( depthImageFrame );
_depthBitmap.WritePixels( new System.Windows.Int32Rect( 0, 0, _depthBitmap.PixelWidth, _depthBitmap.PixelHeight ), _depthPixels,
_depthBitmap.PixelWidth * sizeof( int ), 0 );
return _depthBitmap;
}
/// <summary>
/// Generate different colored pixels for different players
/// </summary>
/// <param name="depthFrame">DepthImageFrame</param>
short[] _rawDepthFrameData;
Byte[] _coloredPixels;
public byte[] GenerateColoredPixels( DepthImageFrame depthFrame )
{
using (depthFrame)
{
if (_rawDepthFrameData == null)
_rawDepthFrameData = new short[depthFrame.PixelDataLength];
depthFrame.CopyPixelDataTo( _rawDepthFrameData );
if (_coloredPixels == null)
_coloredPixels = new Byte[depthFrame.Width * depthFrame.Height * 4];
const int BlueIndex = 0;
const int GreenIndex = 1;
const int RedIndex = 2;
for (int depthIndex = 0, colorIndex = 0; depthIndex < _rawDepthFrameData.Length && colorIndex < _coloredPixels.Length; depthIndex++, colorIndex += 4)
{
int player = _rawDepthFrameData[depthIndex] & DepthImageFrame.PlayerIndexBitmask;
if (player > 0)
{
int blueColor = Convert.ToInt32( Math.Pow( player, 3 ) ) + 100;
int greenColor = Convert.ToInt32( Math.Pow( player, 3 ) ) + 180;
int redColor = Convert.ToInt32( Math.Pow( player, 3 ) ) + 200;
if (blueColor > 255)
blueColor = 255;
if (greenColor > 255)
greenColor = 255;
if (redColor > 255)
redColor = 255;
_coloredPixels[colorIndex + BlueIndex] = Convert.ToByte( blueColor );
_coloredPixels[colorIndex + GreenIndex] = Convert.ToByte( greenColor );
_coloredPixels[colorIndex + RedIndex] = Convert.ToByte( redColor );
}
else
{
_coloredPixels[colorIndex + BlueIndex] = 0;
_coloredPixels[colorIndex + GreenIndex] = 0;
_coloredPixels[colorIndex + RedIndex] = 0;
}
}
return _coloredPixels;
}
}
#endregion
/// <summary>
/// Returns available skeletons
/// </summary>
/// <param name="e">SkeletonFrameReadyEventArgs</param>
public Skeleton[] GetTrackedSkeletons(SkeletonFrame skeletonFrame)
{
using (skeletonFrame)
{
if (skeletonFrame == null)
return null;
Skeleton[] allSkeletons = new Skeleton[6];
skeletonFrame.CopySkeletonDataTo(allSkeletons);
int playerCount = (from s in allSkeletons where s.TrackingState == SkeletonTrackingState.Tracked select s).Count();
if (playerCount == 0)
return null;
Skeleton[] trackedSkeletons = new Skeleton[playerCount];
for (int i = 0; i < playerCount; i++)
trackedSkeletons[i] = (from s in allSkeletons where s.TrackingState == SkeletonTrackingState.Tracked select s).ElementAt(i);
return trackedSkeletons;
}
}
/// <summary>
/// Returns tru if the floor is visible, otherwise returns false
/// </summary>
/// <param name="e">SkeletonFrameReadyEventArgs</param>
public bool IsFloorVisible(SkeletonFrameReadyEventArgs e)
{
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame == null || e == null)
return false;
bool floorVisibility = false;
if (skeletonFrame.FloorClipPlane.Item1 == 0 && skeletonFrame.FloorClipPlane.Item2 == 0 && skeletonFrame.FloorClipPlane.Item3 == 0 && skeletonFrame.FloorClipPlane.Item4 == 0)
floorVisibility = false;
else
floorVisibility = true;
return floorVisibility;
}
}
/// <summary>
/// Takes a SkeletonFrameReadyEventArgs and a joint and return the distance of that joint to floor if the floor is visible, otherwise returns -1
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public double GetDistanceFromFloor(SkeletonFrameReadyEventArgs e, Joint joint)
{
using (SkeletonFrame skeletonData = e.OpenSkeletonFrame())
{
if (skeletonData == null || joint == null)
return -1;
//If floor isn't visible, can't get the distance
if (IsFloorVisible(e) == false)
return -1;
double distanceFromFloor = 0.0d;
double floorClipPlaneX = skeletonData.FloorClipPlane.Item1;
double floorClipPlaneY = skeletonData.FloorClipPlane.Item2;
double floorClipPlaneZ = skeletonData.FloorClipPlane.Item3;
double floorClipPlaneW = skeletonData.FloorClipPlane.Item4;
double hipCenterX = joint.Position.X;
double hipCenterY = joint.Position.Y;
double hipCenterZ = joint.Position.Z;
distanceFromFloor = floorClipPlaneX * hipCenterX + floorClipPlaneY * hipCenterY + floorClipPlaneZ * hipCenterZ + floorClipPlaneW;
return distanceFromFloor;
}
}
}
/// <summary>
/// Provides a dummy client for InteractionStream
/// </summary>
public abstract class FUIInteractionClient
{
public class DummyInteractionClient : Microsoft.Kinect.Toolkit.Interaction.IInteractionClient
{
Microsoft.Kinect.Toolkit.Interaction.InteractionInfo Microsoft.Kinect.Toolkit.Interaction.IInteractionClient.GetInteractionInfoAtLocation(int skeletonTrackingId, InteractionHandType handType, double x, double y)
{
Microsoft.Kinect.Toolkit.Interaction.InteractionInfo result = new Microsoft.Kinect.Toolkit.Interaction.InteractionInfo();
result.IsGripTarget = true;
result.IsPressTarget = true;
result.PressAttractionPointX = 0.5;
result.PressAttractionPointY = 0.5;
result.PressTargetControlId = 1;
return result;
}
}
public sealed class InteractionInfo
{
public bool IsPressTarget { get; set; }
public int PressTargetControlId { get; set; }
public double PressAttractionPointX { get; set; }
public double PressAttractionPointY { get; set; }
public bool IsGripTarget { get; set; }
}
public interface IInteractionClient
{
InteractionInfo GetInteractionInfoAtLocation(int skeletonTrackingId, InteractionHandType handType, double x, double y);
}
}
/// <summary>
/// Used for detecting gestures involving only hands. Such as swipe gestures, grip gestures, pinch gesture
/// </summary>
public class FUHandGestureDetector
{
#region Swipe Detection
const int _SwipeMinimalDuration = 100;
const int _SwipeMaximalDuration = 1000;
DateTime _startTimeSwipeRight = DateTime.Today, _startTimeSwipeLeft = DateTime.Today;
bool _isOnRight = false;
bool _isOnLeft = false;
/// <summary>
/// Takes a skeleton hand returns true when swipe left gesture is performed
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public bool DetectSwipeLeftGesture(Skeleton skeleton)
{
if (skeleton == null)
return false;
bool swipeDetected = false;
#region Swipe Availability Check
//If the hand is below the elbow, no swipe gesture...
if (skeleton.Joints[JointType.HandRight].Position.Y < skeleton.Joints[JointType.ElbowRight].Position.Y)
{
_startTimeSwipeRight = DateTime.Today;
_isOnRight = false;
return false;
}
//If the hand is over the head, no swipe gesture...
if (skeleton.Joints[JointType.HandRight].Position.Y > skeleton.Joints[JointType.Head].Position.Y)
{
_startTimeSwipeRight = DateTime.Today;
_isOnRight = false;
return false;
}
//If the hand is below hip, no swipe gesture...
if (skeleton.Joints[JointType.HandRight].Position.Y < skeleton.Joints[JointType.HipCenter].Position.Y)
{
_startTimeSwipeRight = DateTime.Today;
_isOnRight = false;
return false;
}
SkeletonPoint rightHandPosition = skeleton.Joints[JointType.HandRight].Position;
SkeletonPoint rightShoulderPosition = skeleton.Joints[JointType.ShoulderRight].Position;
//If hand is on the right of the right shoulder, start the gesture scanning when the right hand is on the soulder
if (rightHandPosition.X >= rightShoulderPosition.X)
{
//If the hand is too far on the right, no swipe gesture...
if (rightHandPosition.X - rightShoulderPosition.X > rightShoulderPosition.X - skeleton.Joints[JointType.ShoulderCenter].Position.X)
{
_startTimeSwipeRight = DateTime.Today;
_isOnRight = false;
return false;
}
_isOnRight = true;
}
#endregion
if (_isOnRight)
{
if (_startTimeSwipeRight == DateTime.Today)
_startTimeSwipeRight = DateTime.Now;
DateTime endTime = DateTime.Now;
if (rightHandPosition.X <= skeleton.Joints[JointType.ShoulderCenter].Position.X && (endTime - _startTimeSwipeRight).TotalMilliseconds < _SwipeMaximalDuration
&& (endTime - _startTimeSwipeRight).TotalMilliseconds > _SwipeMinimalDuration)
{
swipeDetected = true;
_startTimeSwipeRight = DateTime.Today;
_isOnRight = false;
}
}
return swipeDetected;
}
/// <summary>
/// Takes a skeleton hand returns true when swipe right gesture is performed
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public bool DetectSwipeRightGesture(Skeleton skeleton)
{
if (skeleton == null)
return false;
bool swipeDetected = false;
#region Swipe Availability Check
//If the hand is below the elbow, no swipe gesture...
if (skeleton.Joints[JointType.HandLeft].Position.Y < skeleton.Joints[JointType.ElbowLeft].Position.Y)
{
_startTimeSwipeLeft = DateTime.Today;
_isOnLeft = false;
return false;
}
//If the hand is over the head, no swipe gesture...
if (skeleton.Joints[JointType.HandLeft].Position.Y > skeleton.Joints[JointType.Head].Position.Y)
{
_startTimeSwipeLeft = DateTime.Today;
_isOnLeft = false;
return false;
}
//If the hand is below hip, no swipe gesture...
if (skeleton.Joints[JointType.HandLeft].Position.Y < skeleton.Joints[JointType.HipCenter].Position.Y)
{
_startTimeSwipeLeft = DateTime.Today;
_isOnLeft = false;
return false;
}
SkeletonPoint leftHandPosition = skeleton.Joints[JointType.HandLeft].Position;
SkeletonPoint leftShoulderPosition = skeleton.Joints[JointType.ShoulderLeft].Position;
//If hand is on the left of the left shoulder, start the gesture scanning when the right hand is on the soulder
if (leftHandPosition.X <= leftShoulderPosition.X)
{
//If the hand is too far on the right, no swipe gesture...
if (leftHandPosition.X - leftShoulderPosition.X < leftShoulderPosition.X - skeleton.Joints[JointType.ShoulderCenter].Position.X)
{
_startTimeSwipeLeft = DateTime.Today;
_isOnLeft = false;
return false;
}
_isOnLeft = true;
}
#endregion
if (_isOnLeft)
{
if (_startTimeSwipeLeft == DateTime.Today)
_startTimeSwipeLeft = DateTime.Now;
DateTime endTime = DateTime.Now;
if (leftHandPosition.X >= skeleton.Joints[JointType.ShoulderCenter].Position.X && (endTime - _startTimeSwipeLeft).TotalMilliseconds < _SwipeMaximalDuration
&& (endTime - _startTimeSwipeLeft).TotalMilliseconds > _SwipeMinimalDuration)
{
swipeDetected = true;
_startTimeSwipeLeft = DateTime.Today;
_isOnLeft = false;
}
}
return swipeDetected;
}
#endregion
#region Grip Detection
private UserInfo[] _userInfosGripping; //the information about the interactive users
private Dictionary<int, InteractionHandEventType> _lastLeftHandEvents = new Dictionary<int, InteractionHandEventType>();
private Dictionary<int, InteractionHandEventType> _lastRightHandEvents = new Dictionary<int, InteractionHandEventType>();
/// <summary>
/// Takes InteractionFrame and returns the gripping hands in a Dictionary.
/// Integer value is the tracking ID of the skeleton and the nested Dictionary returns the InteractionHandEventType variable for the given InteractionHandType
/// Returns null if the InteractionFrame is null
/// </summary>
/// <param name="interactionFrame">InteractionFrame</param>
public Dictionary<int, Dictionary<InteractionHandType, InteractionHandEventType>> DetectGripping(InteractionFrame interactionFrame)
{
if (_userInfosGripping == null)
_userInfosGripping = new UserInfo[InteractionFrame.UserInfoArrayLength];
Dictionary<int, Dictionary<InteractionHandType, InteractionHandEventType>> gripDictionary = new Dictionary<int, Dictionary<InteractionHandType, InteractionHandEventType>>();
using (interactionFrame)
{
if (interactionFrame == null)
return null;
interactionFrame.CopyInteractionDataTo(_userInfosGripping);
}
foreach (UserInfo userInfo in _userInfosGripping)
{
int userID = userInfo.SkeletonTrackingId;
if (userID == 0)
continue;
Dictionary<InteractionHandType, InteractionHandEventType> handDictionary = new Dictionary<InteractionHandType, InteractionHandEventType>();
var handPointers = userInfo.HandPointers;
if (handPointers.Count() == 0)
continue;
else
{
if (handPointers.Count() == 2 && handPointers.ElementAt(0).HandType == InteractionHandType.None &&
handPointers.ElementAt(1).HandType == InteractionHandType.None)
continue;
foreach (var hand in handPointers)
{
var lastHandEvents = hand.HandType == InteractionHandType.Left ? _lastLeftHandEvents : _lastRightHandEvents;
if (hand.HandEventType != InteractionHandEventType.None)
lastHandEvents[userID] = hand.HandEventType;
var lastHandEvent = lastHandEvents.ContainsKey(userID) ? lastHandEvents[userID] : InteractionHandEventType.None;
handDictionary.Add(hand.HandType, lastHandEvent);
}
}
gripDictionary.Add(userID, handDictionary);
}
return gripDictionary;
}
#endregion
#region Press Detection
private UserInfo[] _userInfosPressing; //the information about the interactive users
/// <summary>
/// Takes InteractionFrame and returns the pressing hands in a Dictionary.
/// Integer value is the tracking ID of the skeleton and the nested Dictionary returns the boolean variable for the given InteractionHandType
/// Returns null if the InteractionFrame is null
/// </summary>
/// <param name="interactionFrame">InteractionFrame</param>
public Dictionary<int, Dictionary<InteractionHandType, bool>> DetectPressing(InteractionFrame interactionFrame)
{
if (_userInfosPressing == null)
_userInfosPressing = new UserInfo[InteractionFrame.UserInfoArrayLength];
Dictionary<int, Dictionary<InteractionHandType, bool>> pressDictionary = new Dictionary<int, Dictionary<InteractionHandType, bool>>();
using (interactionFrame)
{
if (interactionFrame == null)
return null;
interactionFrame.CopyInteractionDataTo(_userInfosPressing);
}
foreach (UserInfo userInfo in _userInfosPressing)
{
int userID = userInfo.SkeletonTrackingId;
if (userID == 0)
continue;
Dictionary<InteractionHandType, bool> handDictionary = new Dictionary<InteractionHandType, bool>();
var handPointers = userInfo.HandPointers;
if (handPointers.Count() == 0)
continue;
else
{
if (handPointers.Count() == 2 && handPointers.ElementAt(0).HandType == InteractionHandType.None &&
handPointers.ElementAt(1).HandType == InteractionHandType.None)
continue;
foreach (var hand in handPointers)
{
handDictionary.Add(hand.HandType, hand.IsPressed);
}
}
pressDictionary.Add(userID, handDictionary);
}
return pressDictionary;
}
#endregion
}
/// <summary>
/// Used for detecting postures, like hand up, foot up...
/// </summary>
public class FUPostureDetector
{
/// <summary>
/// Detects the greater sign
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectGreaterPosture(Skeleton skeleton)
{
if (skeleton == null)
return false;
SkeletonPoint leftHandPosition = skeleton.Joints[JointType.HandLeft].Position;
SkeletonPoint rightHandPosition = skeleton.Joints[JointType.HandRight].Position;
SkeletonPoint leftHipPosition = skeleton.Joints[JointType.HipLeft].Position;
SkeletonPoint rightHipPosition = skeleton.Joints[JointType.HipRight].Position;
SkeletonPoint rightShoulderPosition = skeleton.Joints[JointType.ShoulderRight].Position;
SkeletonPoint leftShoulderPosition = skeleton.Joints[JointType.ShoulderLeft].Position;
if ((leftHandPosition.X > leftShoulderPosition.X || leftHandPosition.Y - leftShoulderPosition.Y < 0.2))
return false;
if (Math.Abs(rightHandPosition.Y - leftHipPosition.Y) > 0.1 || rightHandPosition.X > leftHipPosition.X)
return false;
return true;
}
/// <summary>
/// Detects the lesser sign
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectLesserPosture(Skeleton skeleton)
{
if (skeleton == null)
return false;
SkeletonPoint leftHandPosition = skeleton.Joints[JointType.HandLeft].Position;
SkeletonPoint rightHandPosition = skeleton.Joints[JointType.HandRight].Position;
SkeletonPoint leftHipPosition = skeleton.Joints[JointType.HipLeft].Position;
SkeletonPoint rightHipPosition = skeleton.Joints[JointType.HipRight].Position;
SkeletonPoint rightShoulderPosition = skeleton.Joints[JointType.ShoulderRight].Position;
if (rightHandPosition.X - rightHipPosition.X < 0.2)
return false;
if (leftHandPosition.X < rightShoulderPosition.X || leftHandPosition.Y - rightShoulderPosition.Y < 0.2)
return false;
return true;
}
//TODO: Don't count it as jumping while getting close to Kinect
bool _jumped = false;
/// <summary>
/// Detects jumping
/// </summary>
/// <param name="e">SkeletonFrameReadyEventArgs</param>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectJumping( SkeletonFrameReadyEventArgs e, Skeleton skeleton )
{
bool didJump = false;
if (skeleton == null)
return didJump;
//If floor isn't visible, can't do anything
if (IsFloorVisible( e ) == false)
return false;
if (_jumped == true && GetDistanceFromFloor( e, skeleton.Joints[JointType.FootLeft] ) < 0.02d && GetDistanceFromFloor( e, skeleton.Joints[JointType.FootRight] ) < 0.02d)
{
_jumped = false;
return false;
}
if (_jumped == true)
return false;
if (_jumped == false && GetDistanceFromFloor( e, skeleton.Joints[JointType.FootLeft] ) > 0.06d && GetDistanceFromFloor( e, skeleton.Joints[JointType.FootRight] ) > 0.06d)
{
_jumped = true;
didJump = true;
}
return didJump;
}
/// <summary>
/// Takes a skeleton and a SkeletonFrameReadyEventArgs and returns true when user performs right foot up posture
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
/// <param name="e">SkeletonFrameReadyEventArgs</param>
public bool DetectRightFootUpPosture( SkeletonFrameReadyEventArgs e, Skeleton skeleton )
{
if (skeleton == null || e == null)
return false;
//If floor isn't visible, can't do anything
if (IsFloorVisible( e ) == false)
return false;
double rightKneeHeight = GetDistanceFromFloor( e, skeleton.Joints[JointType.KneeRight] );
bool isRightFootUp = false;
if (GetDistanceFromFloor( e, skeleton.Joints[JointType.FootRight] ) > rightKneeHeight / 2.4)
isRightFootUp = true;
else
isRightFootUp = false;
return isRightFootUp;
}
/// <summary>
/// Takes a skeleton and a SkeletonFrameReadyEventArgs and returns true when user performs left foot up posture
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
/// <param name="e">SkeletonFrameReadyEventArgs</param>
public bool DetectLeftFootUpPosture( SkeletonFrameReadyEventArgs e, Skeleton skeleton )
{
if (skeleton == null || e == null)
return false;
//If floor isn't visible, can't do anything
if (IsFloorVisible( e ) == false)
return false;
double leftKneeHeight = GetDistanceFromFloor( e, skeleton.Joints[JointType.KneeLeft] );
bool isLeftFootUp = false;
if (GetDistanceFromFloor( e, skeleton.Joints[JointType.FootLeft] ) > leftKneeHeight / 2.4)
isLeftFootUp = true;
else
isLeftFootUp = false;
return isLeftFootUp;
}
/// <summary>
/// Takes a skeleton and returns true when user performs left hand up posture
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public bool DetectLeftHandUpPosture( Skeleton skeleton )
{
bool isLeftHandUp = false;
if (skeleton == null)
return false;
//Elbow should be under hand
if (skeleton.Joints[JointType.ElbowLeft].Position.Y > skeleton.Joints[JointType.HandLeft].Position.Y)
return false;
if (skeleton.Joints[JointType.HandLeft].Position.Y >= skeleton.Joints[JointType.Head].Position.Y)
isLeftHandUp = true;
else
isLeftHandUp = false;
return isLeftHandUp;
}
/// <summary>
/// Takes a skeleton and returns true when user performs right hand up posture
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public bool DetectRightHandUpPosture( Skeleton skeleton )
{
bool isRightHandUp = false;
if (skeleton == null)
return false;
//Elbow should be under hand
if (skeleton.Joints[JointType.ElbowRight].Position.Y > skeleton.Joints[JointType.HandRight].Position.Y)
return false;
if (skeleton.Joints[JointType.HandRight].Position.Y >= skeleton.Joints[JointType.Head].Position.Y)
isRightHandUp = true;
else
isRightHandUp = false;
return isRightHandUp;
}
/// <summary>
/// Takes a skeleton and returns true when user's left hand is down
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public bool DetectLeftHandDownPosture(Skeleton skeleton)
{
bool isLeftHandDown = false;
if (skeleton == null)
return false;
//Elbow should be over hand
if (skeleton.Joints[JointType.ElbowLeft].Position.Y < skeleton.Joints[JointType.HandLeft].Position.Y)
return false;
if (skeleton.Joints[JointType.HandLeft].Position.Y < skeleton.Joints[JointType.Head].Position.Y)
isLeftHandDown = true;
else
isLeftHandDown = false;
return isLeftHandDown;
}
/// <summary>
/// Takes a skeleton and returns true when user's right hand is down
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public bool DetectRightHandDownPosture(Skeleton skeleton)
{
bool isRightHandDown = false;
if (skeleton == null)
return false;
//Elbow should be over hand
if (skeleton.Joints[JointType.ElbowRight].Position.Y < skeleton.Joints[JointType.HandRight].Position.Y)
return false;
if (skeleton.Joints[JointType.HandRight].Position.Y < skeleton.Joints[JointType.Head].Position.Y)
isRightHandDown = true;
else
isRightHandDown = false;
return isRightHandDown;
}
/// <summary>
/// Takes a skeleton and returns true when user performs both hands up posture
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public bool DetectBothHandsUpPosture(Skeleton skeleton)
{
return DetectRightHandUpPosture(skeleton) && DetectLeftHandUpPosture(skeleton);
}
/// <summary>
/// Returns tru if the floor is visible, otherwise returns false
/// </summary>
/// <param name="e">SkeletonFrameReadyEventArgs</param>
public bool IsFloorVisible(SkeletonFrameReadyEventArgs e)
{
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame == null || e == null)
return false;
bool floorVisibility = false;
if (skeletonFrame.FloorClipPlane.Item1 == 0 && skeletonFrame.FloorClipPlane.Item2 == 0 && skeletonFrame.FloorClipPlane.Item3 == 0 && skeletonFrame.FloorClipPlane.Item4 == 0)
floorVisibility = false;
else
floorVisibility = true;
return floorVisibility;
}
}
/// <summary>
/// Takes a SkeletonFrameReadyEventArgs and a joint and return the distance of that joint to floor if the floor is visible, otherwise returns -1
/// </summary>
/// <param name="skeleton">Tracked skeleton.</param>
public double GetDistanceFromFloor( SkeletonFrameReadyEventArgs e, Joint joint )
{
using (SkeletonFrame skeletonData = e.OpenSkeletonFrame())
{
if (skeletonData == null || joint == null)
return -1;
//If floor isn't visible, can't get the distance
if (IsFloorVisible( e ) == false)
return -1;
double distanceFromFloor = 0.0d;
double floorClipPlaneX = skeletonData.FloorClipPlane.Item1;
double floorClipPlaneY = skeletonData.FloorClipPlane.Item2;
double floorClipPlaneZ = skeletonData.FloorClipPlane.Item3;
double floorClipPlaneW = skeletonData.FloorClipPlane.Item4;
double hipCenterX = joint.Position.X;
double hipCenterY = joint.Position.Y;
double hipCenterZ = joint.Position.Z;
distanceFromFloor = floorClipPlaneX * hipCenterX + floorClipPlaneY * hipCenterY + floorClipPlaneZ * hipCenterZ + floorClipPlaneW;
return distanceFromFloor;
}
}
/// <summary>
/// Checks if the right arm is open as a straight line
/// </summary>
/// <param name="skeleton">Tracked Skeleton</param>
public bool DetectOpenRightArm( Skeleton skeleton )
{
if (skeleton == null)
return false;
bool armOpen = true;
SkeletonPoint rightHandPoint = skeleton.Joints[JointType.HandRight].Position;
SkeletonPoint rightElbowPoint = skeleton.Joints[JointType.ElbowRight].Position;
SkeletonPoint rightShoulderPoint = skeleton.Joints[JointType.ShoulderRight].Position;
//If elbow is below the shoulder, return false
if (rightShoulderPoint.Y - rightElbowPoint.Y > 0.1)
return false;
//If elbow is over shoulder, return false
if (rightShoulderPoint.Y - rightElbowPoint.Y < -0.1)
return false;
//If hand is below elbow, return false
if (rightHandPoint.Y - rightElbowPoint.Y > 0.1)
return false;
//If the hand is over elbow, return false
if (rightHandPoint.Y - rightElbowPoint.Y < -0.1)
return false;
return armOpen;
}
/// <summary>
/// Checks if the left arm is open as a straight line
/// </summary>
/// <param name="skeleton">Tracked Skeleton</param>
public bool DetectOpenLeftArm( Skeleton skeleton )
{
if (skeleton == null)
return false;
bool armOpen = true;
SkeletonPoint leftHandPoint = skeleton.Joints[JointType.HandLeft].Position;
SkeletonPoint leftElbowPoint = skeleton.Joints[JointType.ElbowLeft].Position;
SkeletonPoint leftShoulderPoint = skeleton.Joints[JointType.ShoulderLeft].Position;
//If elbow is below the shoulder, return false
if (leftShoulderPoint.Y - leftElbowPoint.Y > 0.15)
return false;
//If elbow is over shoulder, return false
if (leftShoulderPoint.Y - leftElbowPoint.Y < -0.15)
return false;
//If hand is below elbow, return false
if (leftHandPoint.Y - leftElbowPoint.Y > 0.15)
return false;
//If the hand is over elbow, return false
if (leftHandPoint.Y - leftElbowPoint.Y < -0.15)
return false;
return armOpen;
}
/// <summary>
/// Returns true if both arms open
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectOpenArms( Skeleton skeleton )
{
if (skeleton == null)
return false;
bool isArmsOpen = false;
if (DetectOpenLeftArm( skeleton ) && DetectOpenRightArm( skeleton ))
return true;
return isArmsOpen;
}
/// <summary>
/// Checks if the user is crouching
/// </summary>
/// <param name="e">SkeletonFrameReadyEventArgs: cannot be null</param>
/// <param name="skeleton">Detected Skeleton: Cannot be null</param>
public bool DetectCrouching( SkeletonFrameReadyEventArgs e, Skeleton skeleton )
{
if (e == null || skeleton == null)
return false;
bool isCrouching = true;
if (GetDistanceFromFloor( e, skeleton.Joints[JointType.HipRight] ) <= 0.3 || GetDistanceFromFloor( e, skeleton.Joints[JointType.KneeLeft] ) <= 0.3)
isCrouching = true;
else
isCrouching = false;
return isCrouching;
}
/// <summary>
/// Returns tru if the user is standing or else false, floor must be visible
/// </summary>
/// <param name="e">SkeletonFrameReadyEventArgs: cannot be null</param>
/// <param name="skeleton">Detected Skeleton: Cannot be null</param>
public bool DetectStanding( SkeletonFrameReadyEventArgs e, Skeleton skeleton )
{
if (e == null || skeleton == null)
return false;
if (!IsFloorVisible( e ))
return false;
bool isStanding = true;
SkeletonPoint kneeRightPoint = skeleton.Joints[JointType.KneeRight].Position;
SkeletonPoint kneeLeftPoint = skeleton.Joints[JointType.KneeLeft].Position;
SkeletonPoint footLeftPoint = skeleton.Joints[JointType.FootLeft].Position;
SkeletonPoint footRightPoint = skeleton.Joints[JointType.FootRight].Position;
SkeletonPoint hipCenterPoint = skeleton.Joints[JointType.HipCenter].Position;
SkeletonPoint headPoint = skeleton.Joints[JointType.Head].Position;
//Feet must be on the floor
if (GetDistanceFromFloor( e, skeleton.Joints[JointType.FootLeft] ) > 0.03 || GetDistanceFromFloor( e, skeleton.Joints[JointType.FootRight] ) > 0.03)
return false;
//Knees must be over feet
if (kneeLeftPoint.Y < footLeftPoint.Y || kneeRightPoint.Y < footRightPoint.Y)
return false;
//Head must be over hip center
if (headPoint.Y < hipCenterPoint.Y)
return false;
//Hip center must be at least as high as the distance between knees and the hip center
if (hipCenterPoint.Z > headPoint.Z)
return false;
return isStanding;
}
/// <summary>
/// Returns true if the user is bending over
/// </summary>
/// <param name="skeleton">Tracked Skeleton</param>
public bool DetectBendOver( Skeleton skeleton )
{
if (skeleton == null)
return false;
bool isBendingOver = false;
double shoulderCenterToHipCenterLength = skeleton.Joints[JointType.ShoulderCenter].Position.Y - skeleton.Joints[JointType.HipCenter].Position.Y;
double skeletonPositionZ = skeleton.Position.Z;
//If head isn't over the hip, return false
if (shoulderCenterToHipCenterLength < 0)
return false;
if (skeletonPositionZ - skeleton.Joints[JointType.Head].Position.Z > shoulderCenterToHipCenterLength / 2)
isBendingOver = true;
return isBendingOver;
}
/// <summary>
/// Returns the right arm angle to the right shoulder in an array. First element is the angle between right arm and Y axis,
/// second element is the angle between the right arm and Z axis. Values below zero indicate the direction, below zero is left.
/// </summary>
/// <param name="skeleton">Tracked Skeleton</param>
public double[] DetectRightHandAngle( Skeleton skeleton )
{
if (skeleton == null)
return null;
double[] angles = new double[2];
double angleY, angleZ;
SkeletonPoint rightHandPoint = skeleton.Joints[JointType.HandRight].Position;
SkeletonPoint rightShoulderPoint = skeleton.Joints[JointType.ShoulderRight].Position;
double x = rightHandPoint.X - rightShoulderPoint.X;
double y = rightHandPoint.Y - rightShoulderPoint.Y;
double z = rightHandPoint.Z - rightShoulderPoint.Z;
Vector3D vector1 = new Vector3D( x, y, z );
Vector3D vector2 = new Vector3D( x, 0, z );
angleY = y < 0 ? Vector3D.AngleBetween( vector1, vector2 ) * -1 : Vector3D.AngleBetween( vector1, vector2 );
vector2 = new Vector3D( 0, y, z );
angleZ = x < 0 ? Vector3D.AngleBetween( vector1, vector2 ) * -1 : Vector3D.AngleBetween( vector1, vector2 );
angles[0] = angleY;
angles[1] = angleZ;
return angles;
}
/// <summary>
/// Returns the left arm angle to the left shoulder in an array. First element is the angle between left arm and Y axis,
/// second element is the angle between the left arm and Z axis. Values below zero indicate the direction, below zero is left
/// </summary>
/// <param name="skeleton">Tracked Skeleton</param>
public double[] DetectLeftHandAngle( Skeleton skeleton )
{
if (skeleton == null)
return null;
double[] angles = new double[2];
double angleY, angleZ;
SkeletonPoint leftHandPoint = skeleton.Joints[JointType.HandLeft].Position;
SkeletonPoint leftShoulderPoint = skeleton.Joints[JointType.ShoulderLeft].Position;
//Take the shoulder as the origin for the angle calculation
double x = leftHandPoint.X - leftShoulderPoint.X;
double y = leftHandPoint.Y - leftShoulderPoint.Y;
double z = leftHandPoint.Z - leftShoulderPoint.Z;
Vector3D vector1 = new Vector3D( x, y, z );
Vector3D vector2 = new Vector3D( x, 0, z );
angleY = y < 0 ? Vector3D.AngleBetween( vector1, vector2 ) * -1 : Vector3D.AngleBetween( vector1, vector2 );
vector2 = new Vector3D( 0, y, z );
angleZ = x < 0 ? Vector3D.AngleBetween( vector1, vector2 ) * -1 : Vector3D.AngleBetween( vector1, vector2 );
angles[0] = angleY;
angles[1] = angleZ;
return angles;
}
/// <summary>
/// Returns true if the arms are crossed in a cross gesture. NEEDS IMPROVEMENT
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectCrossPosture( Skeleton skeleton )
{
//TODO: Check if Z angles matter
if (skeleton == null)
return false;
return DetectSlashPostureForRightArm( skeleton ) && DetectSlashPostureForLeftArm( skeleton );
}
/// <summary>
/// Returns true if any of the arms are in a slash posture
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectSlashPosture( Skeleton skeleton )
{
if (skeleton == null)
return false;
bool isSlashPosture = false;
if (DetectSlashPostureForRightArm(skeleton))
{
//left hand should be down
if (skeleton.Joints[JointType.HandLeft].Position.Y > skeleton.Joints[JointType.HipCenter].Position.Y)
return false;
isSlashPosture = true;
}
else if (DetectSlashPostureForLeftArm(skeleton))
{
//Right hand should be down
if (skeleton.Joints[JointType.HandRight].Position.Y > skeleton.Joints[JointType.HipCenter].Position.Y)
return false;
isSlashPosture = true;
}
return isSlashPosture;
}
/// <summary>
/// Returns true if right arm is in a slash posture
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectSlashPostureForRightArm( Skeleton skeleton )
{
//TODO: Check if Z angles matter
if (skeleton == null)
return false;
SkeletonPoint rightHandPoint = skeleton.Joints[JointType.HandRight].Position;
SkeletonPoint rightElbowPoint = skeleton.Joints[JointType.ElbowRight].Position;
//If the hand is on the left side of the elbow return false
if (rightHandPoint.X > rightElbowPoint.X)
return false;
//If the hand is below elbow return false
if (rightHandPoint.Y < rightElbowPoint.Y)
return false;
if (rightHandPoint.Y - rightElbowPoint.Y < 0.15 || rightHandPoint.Y - rightElbowPoint.Y > 0.45)
return false;
return true;
}
/// <summary>
/// Returns true if let arm is in a slash posture
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectSlashPostureForLeftArm( Skeleton skeleton )
{
//TODO: Check if Z angles matter
if (skeleton == null)
return false;
SkeletonPoint leftHandPoint = skeleton.Joints[JointType.HandLeft].Position;
SkeletonPoint leftElbowPoint = skeleton.Joints[JointType.ElbowLeft].Position;
//If the hand is on the left side of the elbow return false
if (leftHandPoint.X < leftElbowPoint.X)
return false;
//If the hand is below elbow return false
if (leftHandPoint.Y < leftElbowPoint.Y)
return false;
if (leftHandPoint.Y - leftElbowPoint.Y < 0.15 || leftHandPoint.Y - leftElbowPoint.Y > 0.45)
return false;
return true;
}
/// <summary>
/// Returns true if right arm is in a minus posture
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectMinusPostureForRightArm( Skeleton skeleton )
{
if (skeleton == null)
return false;
SkeletonPoint rightHandPoint = skeleton.Joints[JointType.HandRight].Position;
SkeletonPoint rightElbowPoint = skeleton.Joints[JointType.ElbowRight].Position;
//Left hand should be down
if (skeleton.Joints[JointType.HandLeft].Position.Y > skeleton.Joints[JointType.HipCenter].Position.Y)
return false;
//If hand is below hip center return false
if (rightHandPoint.Y < skeleton.Joints[JointType.HipCenter].Position.Y)
return false;
//If the hand is too much over elbow or too much below elbow return false
if (Math.Abs( rightHandPoint.Y - rightElbowPoint.Y ) > 0.1)
return false;
//If the hand is on the right side of the elbow return false
if (rightHandPoint.X > rightElbowPoint.X)
return false;
return true;
}
/// <summary>
/// Returns true left arm is in a minus posture
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectMinusPostureForLeftArm(Skeleton skeleton)
{
if (skeleton == null)
return false;
SkeletonPoint leftHandPoint = skeleton.Joints[JointType.HandLeft].Position;
SkeletonPoint leftElbowPoint = skeleton.Joints[JointType.ElbowLeft].Position;
//Right hand should be down
if (skeleton.Joints[JointType.HandRight].Position.Y > skeleton.Joints[JointType.HipCenter].Position.Y)
return false;
//If hand is below hip center return false
if (leftHandPoint.Y < skeleton.Joints[JointType.HipCenter].Position.Y)
return false;
//If the hand is too much over elbow or too much below elbow return false
if (Math.Abs(leftHandPoint.Y - leftElbowPoint.Y) > 0.1)
return false;
//If the hand is on the left side of the elbow return false
if (leftHandPoint.X < leftElbowPoint.X)
return false;
return true;
}
/// <summary>
/// Returns true if any of the arms are in a minux posture
/// </summary>
/// <param name="skeleton">Tracked Skeleton</param>
public bool DetectMinusPosture( Skeleton skeleton )
{
if (skeleton == null)
return false;
bool isMinusPosture = false;
if (DetectMinusPostureForLeftArm( skeleton ) || DetectMinusPostureForRightArm( skeleton ))
isMinusPosture = true;
else
isMinusPosture = false;
return isMinusPosture;
}
/// <summary>
/// Returns true if the arms are crossed in a plus posture
/// </summary>
/// <param name="skeleton">Tracked skeleton</param>
public bool DetectPlusPosture( Skeleton skeleton )
{
if (skeleton == null)
return false;
SkeletonPoint leftHandPoint = skeleton.Joints[JointType.HandLeft].Position;
SkeletonPoint leftElbowPoint = skeleton.Joints[JointType.ElbowLeft].Position;
SkeletonPoint rightHandPoint = skeleton.Joints[JointType.HandRight].Position;
SkeletonPoint rightElbowPoint = skeleton.Joints[JointType.ElbowRight].Position;
//If hand is below elbow return false
if (leftHandPoint.Y < leftElbowPoint.Y || rightHandPoint.Y < rightElbowPoint.Y)
return false;
//If hands are below hip center return false
if (rightHandPoint.Y < skeleton.Joints[JointType.HipCenter].Position.Y || leftHandPoint.Y < skeleton.Joints[JointType.HipCenter].Position.Y)
return false;
if (rightHandPoint.X > leftHandPoint.X || leftElbowPoint.X > rightElbowPoint.X)
return false;
if (rightHandPoint.Y > leftHandPoint.Y && (Math.Abs( rightHandPoint.X - rightElbowPoint.X ) > 0.1
&& Math.Abs( leftHandPoint.Y - leftElbowPoint.Y ) > 0.1))
return false;
if (rightHandPoint.Y < leftHandPoint.Y && (Math.Abs( leftHandPoint.X - leftElbowPoint.X ) > 0.1
&& Math.Abs( rightHandPoint.Y - rightElbowPoint.Y ) > 0.1))
return false;
return true;
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.DisposableTypesShouldDeclareFinalizerAnalyzer,
Microsoft.NetCore.CSharp.Analyzers.Runtime.CSharpDisposableTypesShouldDeclareFinalizerFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.DisposableTypesShouldDeclareFinalizerAnalyzer,
Microsoft.NetCore.VisualBasic.Analyzers.Runtime.BasicDisposableTypesShouldDeclareFinalizerFixer>;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class DisposableTypesShouldDeclareFinalizerTests
{
[Fact]
public async Task CSharpDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndNoFinalizerExists()
{
var code = @"
using System;
using System.Runtime.InteropServices;
internal static class NativeMethods
{
[DllImport(""native.dll"")]
internal static extern IntPtr AllocateResource();
}
public class A : IDisposable
{
private readonly IntPtr _pi;
public A()
{
_pi = NativeMethods.AllocateResource();
}
public void Dispose()
{
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpDiagnostic(11, 14));
}
[Fact]
public async Task BasicDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndNoFinalizerExists()
{
var code = @"
Imports System
Imports System.Runtime.InteropServices
Friend Class NativeMethods
<DllImport(""native.dll"")>
Friend Shared Function AllocateResource() As IntPtr
End Function
End Class
Public Class A
Implements IDisposable
Private ReadOnly _pi As IntPtr
Public Sub New()
_pi = NativeMethods.AllocateResource()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicDiagnostic(11, 14));
}
[Fact]
public async Task CSharpNoDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndFinalizerExists()
{
var code = @"
using System;
using System.Runtime.InteropServices;
internal static class NativeMethods
{
[DllImport(""native.dll"")]
internal static extern IntPtr AllocateResource();
}
public class A : IDisposable
{
private readonly IntPtr _pi;
public A()
{
_pi = NativeMethods.AllocateResource();
}
public void Dispose()
{
}
~A()
{
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndFinalizerExists()
{
var code = @"
Imports System
Imports System.Runtime.InteropServices
Friend Class NativeMethods
<DllImport(""native.dll"")>
Friend Shared Function AllocateResource() As IntPtr
End Function
End Class
Public Class A
Implements IDisposable
Private ReadOnly _pi As IntPtr
Public Sub New()
_pi = NativeMethods.AllocateResource()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Protected Overrides Sub Finalize()
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpNoDiagnosticIfIntPtrFieldInValueTypeIsAssignedFromNativeCode()
{
var code = @"
using System;
using System.Runtime.InteropServices;
internal static class NativeMethods
{
[DllImport(""native.dll"")]
internal static extern IntPtr AllocateResource();
}
public struct A : IDisposable // Although disposable structs are evil
{
private readonly IntPtr _pi;
public A(int i)
{
_pi = NativeMethods.AllocateResource();
}
public void Dispose()
{
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticIfIntPtrFieldInValueTypeIsAssignedFromNativeCode()
{
var code = @"
Imports System
Imports System.Runtime.InteropServices
Friend Class NativeMethods
<DllImport(""native.dll"")>
Friend Shared Function AllocateResource() As IntPtr
End Function
End Class
Public Structure A
Implements IDisposable ' Although disposable structs are evil
Private ReadOnly _pi As IntPtr
Public Sub New(i As Integer)
_pi = NativeMethods.AllocateResource()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Structure
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpNoDiagnosticIfIntPtrFieldInNonDisposableTypeIsAssignedFromNativeCode()
{
var code = @"
using System;
using System.Runtime.InteropServices;
internal static class NativeMethods
{
[DllImport(""native.dll"")]
internal static extern IntPtr AllocateResource();
}
public class A
{
private readonly IntPtr _pi;
public A()
{
_pi = NativeMethods.AllocateResource();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticIfIntPtrFieldInNonDisposableTypeIsAssignedFromNativeCode()
{
var code = @"
Imports System
Imports System.Runtime.InteropServices
Friend Class NativeMethods
<DllImport(""native.dll"")>
Friend Shared Function AllocateResource() As IntPtr
End Function
End Class
Public Class A
Private ReadOnly _pi As IntPtr
Public Sub New()
_pi = NativeMethods.AllocateResource()
End Sub
Public Sub Dispose()
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpNoDiagnosticIfIntPtrFieldIsAssignedFromManagedCode()
{
var code = @"
using System;
internal static class ManagedMethods
{
internal static IntPtr AllocateResource()
{
return IntPtr.Zero;
}
}
public class A : IDisposable
{
private readonly IntPtr _pi;
public A()
{
_pi = ManagedMethods.AllocateResource();
}
public void Dispose()
{
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticIfIntPtrFieldIsAssignedFromManagedCode()
{
var code = @"
Imports System
Friend NotInheritable Class ManagedMethods
Friend Shared Function AllocateResource() As IntPtr
Return IntPtr.Zero
End Function
End Class
Public Class A
Implements IDisposable
Private ReadOnly _pi As IntPtr
Public Sub New()
_pi = ManagedMethods.AllocateResource()
End Sub
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpDiagnosticIfUIntPtrFieldIsAssignedFromNativeCode()
{
var code = @"
using System;
using System.Runtime.InteropServices;
internal static class NativeMethods
{
[DllImport(""native.dll"")]
internal static extern UIntPtr AllocateResource();
}
public class A : IDisposable
{
private readonly UIntPtr _pu;
public A()
{
_pu = NativeMethods.AllocateResource();
}
public void Dispose()
{
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpDiagnostic(11, 14));
}
[Fact]
public async Task BasicDiagnosticIfUIntPtrFieldIsAssignedFromNativeCode()
{
var code = @"
Imports System
Imports System.Runtime.InteropServices
Friend Class NativeMethods
<DllImport(""native.dll"")>
Friend Shared Function AllocateResource() As UIntPtr
End Function
End Class
Public Class A
Implements IDisposable
Private ReadOnly _pu As UIntPtr
Public Sub New()
_pu = NativeMethods.AllocateResource()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicDiagnostic(11, 14));
}
[Fact]
public async Task CSharpDiagnosticIfHandleRefFieldIsAssignedFromNativeCode()
{
var code = @"
using System;
using System.Runtime.InteropServices;
internal static class NativeMethods
{
[DllImport(""native.dll"")]
internal static extern HandleRef AllocateResource();
}
public class A : IDisposable
{
private readonly HandleRef _hr;
public A()
{
_hr = NativeMethods.AllocateResource();
}
public void Dispose()
{
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpDiagnostic(11, 14));
}
[Fact]
public async Task BasicDiagnosticIfHandleRefFieldIsAssignedFromNativeCode()
{
var code = @"
Imports System
Imports System.Runtime.InteropServices
Friend Class NativeMethods
<DllImport(""native.dll"")>
Friend Shared Function AllocateResource() As HandleRef
End Function
End Class
Public Class A
Implements IDisposable
Private ReadOnly _hr As HandleRef
Public Sub New()
_hr = NativeMethods.AllocateResource()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicDiagnostic(11, 14));
}
[Fact]
public async Task CSharpNoDiagnosticIfNonNativeResourceFieldIsAssignedFromNativeCode()
{
var code = @"
using System;
using System.Runtime.InteropServices;
internal static class NativeMethods
{
[DllImport(""native.dll"")]
internal static extern int AllocateResource();
}
public class A : IDisposable
{
private readonly int _i;
public A()
{
_i = NativeMethods.AllocateResource();
}
public void Dispose()
{
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicNoDiagnosticIfNonNativeResourceFieldIsAssignedFromNativeCode()
{
var code = @"
Imports System
Imports System.Runtime.InteropServices
Friend Class NativeMethods
<DllImport(""native.dll"")>
Friend Shared Function AllocateResource() As Integer
End Function
End Class
Public Class A
Implements IDisposable
Private ReadOnly _i As Integer
Public Sub New()
_i = NativeMethods.AllocateResource()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
private static DiagnosticResult GetCSharpDiagnostic(int line, int column) =>
VerifyCS.Diagnostic().WithLocation(line, column);
private static DiagnosticResult GetBasicDiagnostic(int line, int column) =>
VerifyVB.Diagnostic().WithLocation(line, column);
}
}
| |
using System;
using System.Linq;
using BaconGameJam6.Models.Games;
using UnityEngine;
using BaconGameJam6.Models.Boards;
using BaconGameJam6.Models.Blocks;
using BaconGameJam6.Models.Player;
using BaconGameJam6.Models.States;
using System.Collections.Generic;
using BaconGameJam6.Models.Simulations;
using BaconGameJam6;
public enum GameLoopState
{
MainMenu,
Playing,
}
public class GameLoopStateEventArgs : EventArgs
{
public GameLoopState GameLoopState { get; private set; }
public GameLoopStateEventArgs(GameLoopState gameLoopState)
{
this.GameLoopState = gameLoopState;
}
}
public enum PlayerStateEvent
{
Joined,
Left,
}
public class PlayerStateEventArgs : EventArgs
{
public PlayerStateEvent PlayerStateEvent { get; private set; }
public PlayerId PlayerId { get; private set; }
public PlayerStateEventArgs(PlayerStateEvent playerStateEvent, PlayerId playerId)
{
this.PlayerStateEvent = playerStateEvent;
this.PlayerId = playerId;
}
}
public class BoardTransform
{
public Vector3 position;
public Vector3 scale;
public BoardTransform(Vector3 position, Vector3 scale)
{
this.position = position;
this.scale = scale;
}
}
public class BoardTransformSet
{
public BoardTransform[] Transforms;
public BoardTransformSet(params float[] args)
{
var count = args.Length / 2;
this.Transforms = new BoardTransform[count];
for (var i = 0; i < count; ++i)
{
float xOffset = args[i * 2];
float scale = args[i * 2 + 1];
this.Transforms[i] = new BoardTransform(new Vector3(xOffset, 0, 0), new Vector3(scale, scale, scale));
}
}
}
public class GameLoop : MonoBehaviour
{
public event EventHandler<GameLoopStateEventArgs> GameLoopStateChanged;
public event EventHandler<PlayerStateEventArgs> PlayerStateChanged;
public GameObject Board;
public List<GameObject> Blocks;
public GameObject Ship;
public GameObject Missile;
private Game game;
private GameObject[] boardsViews;
private static readonly BoardTransformSet[] boardTransformSets =
{
new BoardTransformSet(-4, 1f),
new BoardTransformSet(-8, 1f, 0, 1f),
new BoardTransformSet(-12, 1f, -4, 1f, 4, 1f),
new BoardTransformSet(-14.5f, 1f, -7.5f, 1f, -0.5f, 1f, 6.5f, 1f),
};
private Dictionary<int, GameObject> blockViews;
private List<BlinkingLight> blinkingLights;
private readonly Queue<IState> states = new Queue<IState>();
void Start()
{
this.blinkingLights = new List<BlinkingLight>();
this.game = new Game();
this.boardsViews = new GameObject[this.game.Simulations.Length];
this.blockViews = new Dictionary<int, GameObject>();
this.StartNewGame(2);
}
private GameLoopState gameLoopState;
public GameLoopState GameLoopState
{
get
{
return this.gameLoopState;
}
private set
{
this.gameLoopState = value;
if (this.GameLoopStateChanged != null)
{
this.GameLoopStateChanged.Invoke(this, new GameLoopStateEventArgs(value));
}
}
}
public void StartNewGame(int playerCount)
{
this.GameLoopState = GameLoopState.Playing;
this.game.Start(playerCount);
for (int i = 0; i < playerCount; i++)
{
SpawnBoard(i, playerCount);
}
}
public void EndGame()
{
if (this.game.Simulations != null)
{
for (int i = 0; i < this.game.Simulations.Length; i++)
{
if (this.boardsViews[i] != null)
{
GameObject.Destroy(this.boardsViews[i]);
this.boardsViews[i] = null;
}
this.game.Simulations[i].BlockDestroyed -= SetLights;
if (this.game.Simulations[i].HasPlayer)
{
this.game.RemovePlayer((PlayerId)i);
}
}
}
this.game.Stop();
this.GameLoopState = GameLoopState.MainMenu;
}
void Update()
{
float elapsedTime = Time.deltaTime;
TimeSpan elapsedTimeSpan = TimeSpan.FromSeconds(elapsedTime);
if (this.states.Count > 0)
{
this.states.Peek().Update(elapsedTimeSpan);
if (this.states.Peek().IsComplete)
{
this.states.Dequeue();
}
}
this.ProcessInput(elapsedTime);
if (!this.game.CanUpdate)
{
return;
}
this.game.Update(elapsedTimeSpan);
var seenBlocks = new Dictionary<int, bool>();
for (int i = 0; i < this.game.Simulations.Length; i++)
{
var simulation = this.game.Simulations[i];
if (this.boardsViews[i] != null)
{
foreach (var boardPiece in simulation.Board)
{
if (!this.blockViews.ContainsKey(boardPiece.Id))
{
this.blockViews[boardPiece.Id] = this.CreateViewFor(boardPiece, this.boardsViews[i]);
}
var blockView = this.blockViews[boardPiece.Id];
blockView.SetActive(boardPiece.Y > -1);
blockView.transform.localPosition = new Vector3(boardPiece.X, boardPiece.Y, boardPiece.Z);
bool isShip = blockView.tag.Equals("Ship");
float xPadding = isShip ? 90 : 0;
float yPadding = isShip ? 0 : 90;
if (isShip)
{
this.SetCursorVisiblity((Ship)boardPiece, blockView, this.boardsViews[i]);
blockView.transform.localEulerAngles = new Vector3(xPadding + boardPiece.Rotation, yPadding, 0);
}
else
{
blockView.transform.localEulerAngles = new Vector3(xPadding + boardPiece.Rotation, yPadding + boardPiece.Rotation, boardPiece.Rotation);
}
var color = blockView.renderer.material.color;
color.a = boardPiece.Opacity;
blockView.renderer.material.color = color;
seenBlocks[boardPiece.Id] = true;
}
this.boardsViews[i].transform.localPosition = new Vector3(simulation.Board.TargetPosition.x + simulation.Board.XOffset, simulation.Board.YOffset, 0);
}
}
int[] ids = this.blockViews.Keys.ToArray();
foreach (var id in ids)
{
if (!seenBlocks.ContainsKey(id))
{
DestroyObject(this.blockViews[id]);
this.blockViews.Remove(id);
}
}
for (var i = this.blinkingLights.Count; i > 0; --i)
{
BlinkingLight light = this.blinkingLights[i - 1];
light.Update(elapsedTime);
if (light.IsCompleted)
{
this.blinkingLights.RemoveAt(i - 1);
}
}
}
private float[] ignoreInputTime = new float[4];
private static readonly float IgnoreTime = 0.2f;
private void ProcessInput(float elapsedTime)
{
bool updateBoards = false;
bool hadPlayers = this.game.PlayerCount != 0;
bool canUpdate = this.game.CanUpdate;
for (int i = 0; i < this.game.Simulations.Length; i++)
{
var simulation = this.game.Simulations[i];
int inputId = i + 1;
if (simulation.HasPlayer && canUpdate)
{
bool ignoreInput = false;
if (ignoreInputTime[(int)simulation.PlayerId] > 0f)
{
ignoreInputTime[(int)simulation.PlayerId] -= elapsedTime;
ignoreInput = (ignoreInputTime[(int)simulation.PlayerId] > 0f);
}
ignoreInput = ignoreInput || !simulation.IsActive;
if (!ignoreInput)
{
if (Input.GetAxis("Fire" + inputId) > 0)
{
this.game.OnFire(simulation.PlayerId);
}
else
{
this.game.OnReload(simulation.PlayerId);
}
var horizontal = Input.GetAxis("Horizontal" + inputId);
if (Math.Abs(horizontal) < 0.000005)
{
this.game.OnStopMoving(simulation.PlayerId);
}
else if (horizontal < 0)
{
this.game.OnMoveLeft(simulation.PlayerId);
}
else if (horizontal > 0)
{
this.game.OnMoveRight(simulation.PlayerId);
}
}
if (Input.GetAxis("Back" + inputId) > 0)
{
RemovePlayer(simulation.PlayerId);
updateBoards = true;
}
}
else
{
if ((Input.GetAxis("Fire" + inputId) > 0) || Input.GetAxis("Start" + inputId) > 0)
{
AddPlayer(simulation.PlayerId);
updateBoards = true;
this.ignoreInputTime[(int)simulation.PlayerId] = IgnoreTime;
}
}
}
if (hadPlayers && (this.game.PlayerCount == 0))
{
EndGame();
}
else if (updateBoards)
{
if (!hadPlayers)
{
this.GameLoopState = GameLoopState.Playing;
this.game.Start(0);
}
else
{
UpdateBoards();
}
}
}
private void AddPlayer(PlayerId playerId)
{
this.game.AddPlayer(playerId);
SpawnBoard((int)playerId, this.game.PlayerCount);
if (this.PlayerStateChanged != null)
{
this.PlayerStateChanged(this, new PlayerStateEventArgs(PlayerStateEvent.Joined, playerId));
}
}
private void RemovePlayer(PlayerId playerId)
{
this.game.RemovePlayer(playerId);
var i = (int)playerId;
if (this.boardsViews[i] != null)
{
GameObject.Destroy(this.boardsViews[i]);
this.boardsViews[i] = null;
}
if (this.PlayerStateChanged != null)
{
this.PlayerStateChanged(this, new PlayerStateEventArgs(PlayerStateEvent.Left, playerId));
}
}
private void SpawnBoard(int i, int playerCount)
{
BoardTransformSet boardTransformSet = boardTransformSets[playerCount - 1];
int relativeCount = 0;
for (var ii = 0; ii < this.game.Simulations.Length; ++ii)
{
if (i == ii)
{
break;
}
if (this.game.Simulations[ii].HasPlayer)
{
++relativeCount;
}
}
BoardTransform boardTransform = boardTransformSet.Transforms[relativeCount];
this.boardsViews[i] = Instantiate(Board, boardTransform.position, Quaternion.identity) as GameObject;
this.boardsViews[i].transform.localScale = boardTransform.scale;
this.game.Simulations[i].Board.TargetPosition = boardTransform.position;
this.game.Simulations[i].BlockDestroyed += SetLights;
foreach (BoardPiece boardPiece in this.game.Simulations[i].Board)
{
this.blockViews[boardPiece.Id] = this.CreateViewFor(boardPiece, this.boardsViews[i]);
}
}
private void UpdateBoards()
{
int playerCount = this.game.PlayerCount;
BoardTransformSet boardTransformSet = boardTransformSets[playerCount - 1];
var relative = 0;
for (var i = 0; i < this.game.Simulations.Length; ++i)
{
var simulation = this.game.Simulations[i];
if (simulation.HasPlayer)
{
BoardTransform boardTransform = boardTransformSet.Transforms[relative];
simulation.Board.TargetPosition = boardTransform.position;
++relative;
}
}
// $TODO: animate boards moving and leaving
}
private GameObject CreateViewFor(BoardPiece boardPiece, GameObject parent)
{
GameObject objectToClone = null;
if (boardPiece is Ship)
{
objectToClone = this.Ship;
}
else if (boardPiece is Missile)
{
objectToClone = this.Missile;
}
else
{
Block block = boardPiece as Block;
objectToClone = this.Blocks[(int)block.BlockType];
}
GameObject boardPieceView = Instantiate(objectToClone) as GameObject;
boardPieceView.transform.localPosition = new Vector3(boardPiece.X, boardPiece.Y, boardPiece.Z);
boardPieceView.transform.parent = parent.transform;
return boardPieceView;
}
private void SetLights(object sender, MatchEventArgs args)
{
Simulation simulation = sender as Simulation;
GameObject board = this.boardsViews[simulation.SimulationIndex];
if (null == board)
{
return;
}
Transform[] allChildrenOfBoard = board.GetComponentsInChildren<Transform>();
int lightBulbIndex = 0;
foreach (Transform transform in allChildrenOfBoard)
{
if (transform.tag.Equals("LightBulb"))
{
Color newColor = new Color(0.2f, 0.2f, 0.2f, 1f);
if (lightBulbIndex < args.Blocks.Length)
{
BlockType blockType = args.Blocks[lightBulbIndex].BlockType;
newColor = Utilities.BlockTypeToColor(blockType);
}
this.blinkingLights.RemoveAll(light => (light.Transform == transform));
if (args.Animate)
{
if (transform.renderer.material.color != newColor)
{
this.blinkingLights.Add(new BlinkingLight(simulation, transform, transform.renderer.material.color, newColor, lightBulbIndex, args.IsMatch));
}
}
else
{
transform.renderer.material.color = newColor;
}
++lightBulbIndex;
}
else if (transform.tag.Equals("Ship"))
{
Transform[] allChildrenOfShip = transform.GetComponentsInChildren<Transform>();
foreach (Transform shipChild in allChildrenOfShip)
{
if (shipChild.tag.Equals("AimingLight"))
{
// Set the ship's light to the last block's color, unless the array is empty, in which case set the ship's light color to white.
Color shipLightColor = new Color(1f, 1f, 1f, 1f);
if (args.Blocks.Length > 0)
{
shipLightColor = Utilities.BlockTypeToColor(args.Blocks[args.Blocks.Length - 1].BlockType);
}
shipChild.renderer.material.color = shipLightColor;
}
}
}
else if (transform.tag.Equals("AimingLight"))
{
// Set the ship's light to the last block's color, unless the array is empty, in which case set the ship's light color to white.
Color shipLightColor = new Color(1f, 1f, 1f, 1f);
if (args.Blocks.Length > 0)
{
shipLightColor = Utilities.BlockTypeToColor(args.Blocks[args.Blocks.Length - 1].BlockType);
}
transform.renderer.material.color = shipLightColor;
}
}
}
private void SetCursorVisiblity(Ship ship, GameObject shipView, GameObject boardView)
{
shipView.transform.Find("Plane").gameObject.SetActive(ship.IsActive);
boardView.transform.Find("BottomPlayerLayer").gameObject.SetActive(ship.IsActive);
}
protected void AddState(IState state)
{
this.states.Enqueue(state);
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Premotion.Mansion.Core;
using Premotion.Mansion.Core.Data;
using Premotion.Mansion.Repository.SqlServer.Queries;
namespace Premotion.Mansion.Repository.SqlServer.Schemas
{
/// <summary>
/// Represents a multi-value property table.
/// </summary>
public class MultiValuePropertyTable : Table
{
#region Nested type: MultiValuePropertyColumn
/// <summary>
/// Implements <see cref="Column"/> for single value properties.
/// </summary>
private class MultiValuePropertyColumn : Column
{
#region constructors
/// <summary>
/// </summary>
/// <param name="columnName"></param>
public MultiValuePropertyColumn(string columnName) : base("value", columnName)
{
}
#endregion
#region Overrides of Column
/// <summary>
/// Constructs a WHERE statements on this column for the given <paramref name="values"/>.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <param name="commandContext">The <see cref="QueryCommandContext"/>.</param>
/// <param name="pair">The <see cref="TableColumnPair"/>.</param>
/// <param name="values">The values on which to construct the where statement.</param>
protected override void DoToWhereStatement(IMansionContext context, QueryCommandContext commandContext, TableColumnPair pair, IList<object> values)
{
// assemble the properties
var buffer = new StringBuilder();
foreach (var value in values)
buffer.AppendFormat("@{0},", commandContext.Command.AddParameter(value));
// append the query
commandContext.QueryBuilder.AppendWhere(" [{0}].[id] IN ( SELECT [{1}].[id] FROM [{1}] WHERE [{1}].[name] = '{2}' AND [{1}].[value] IN ({3}) )", commandContext.QueryBuilder.RootTableName, pair.Table.Name, PropertyName, buffer.Trim());
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="queryBuilder"></param>
/// <param name="properties"></param>
protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties)
{
throw new NotSupportedException();
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="queryBuilder"></param>
/// <param name="record"> </param>
/// <param name="modifiedProperties"></param>
protected override void DoToUpdateStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, Record record, IPropertyBag modifiedProperties)
{
throw new NotSupportedException();
}
#endregion
}
#endregion
#region Constructors
/// <summary>
/// Constructs this table with the given <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of this table.</param>
public MultiValuePropertyTable(string name) : base(name)
{
}
#endregion
#region Add Methods
/// <summary>
/// Adds a property name ot this multi valued table.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <returns>Returns this table.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="propertyName"/> is null.</exception>
public MultiValuePropertyTable Add(string propertyName)
{
// validate arguments
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentNullException("propertyName");
// add a column
Add(new MultiValuePropertyColumn(propertyName));
// return this for chaining
return this;
}
#endregion
#region Overrides of Table
/// <summary>
/// Generates the insert statement for this table.
/// </summary>
/// <param name="context"></param>
/// <param name="queryBuilder"></param>
/// <param name="properties"></param>
protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties)
{
// loop through all the properties
foreach (var propertyName in Columns.Select(column => column.PropertyName))
{
// check if there are any properties
var values = properties.Get(context, propertyName, string.Empty).Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();
if (values.Length == 0)
continue;
// loop through each value and write an insert statement
foreach (var value in values)
{
// build the query
var valueModificationQuery = new ModificationQueryBuilder(queryBuilder);
// set column values
valueModificationQuery.AddColumnValue("id", "@ScopeIdentity");
valueModificationQuery.AddColumnValue("name", propertyName, DbType.String);
valueModificationQuery.AddColumnValue("value", value, DbType.String);
// append the query
queryBuilder.AppendQuery(valueModificationQuery.ToInsertStatement(Name));
}
}
}
/// <summary>
/// Generates the update statement for this table.
/// </summary>
/// <param name="context"></param>
/// <param name="queryBuilder"></param>
/// <param name="record"> </param>
/// <param name="modifiedProperties"></param>
protected override void DoToUpdateStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, Record record, IPropertyBag modifiedProperties)
{
// create identity parameter
var idParameterName = queryBuilder.AddParameter("id", record.Id, DbType.Int32);
// loop through all the properties
foreach (var propertyName in Columns.Select(column => column.PropertyName))
{
// check if the property is modified
string rawModifiedValue;
if (!modifiedProperties.TryGet(context, propertyName, out rawModifiedValue))
continue;
// get the current values
var currentValues = GetCurrentValues(queryBuilder.Command, record, propertyName).ToList();
// check if there are new properties
var modifiedValues = (rawModifiedValue ?? string.Empty).Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();
// get the deleted values
var deletedValues = currentValues.Except(modifiedValues, StringComparer.OrdinalIgnoreCase);
var newValues = modifiedValues.Except(currentValues, StringComparer.OrdinalIgnoreCase);
// create property parameter
var propertyParameterName = queryBuilder.AddParameter(propertyName, propertyName, DbType.String);
// generate the delete statements
foreach (var deletedValue in deletedValues)
{
// build the query
var valueModificationQuery = new ModificationQueryBuilder(queryBuilder);
// build clause
var valueParameterName = valueModificationQuery.AddParameter("value", deletedValue, DbType.String);
valueModificationQuery.AppendWhereClause("[id] = " + idParameterName + " AND [name] = " + propertyParameterName + " AND [value] = " + valueParameterName);
// append the query
queryBuilder.AppendQuery(valueModificationQuery.ToDeleteStatement(Name));
}
// generate the insert statements
foreach (var newValue in newValues)
{
// build the query
var valueModificationQuery = new ModificationQueryBuilder(queryBuilder);
// set column values
valueModificationQuery.AddColumnValue("id", idParameterName);
valueModificationQuery.AddColumnValue("name", propertyParameterName);
valueModificationQuery.AddColumnValue("value", newValue, DbType.String);
// append the query
queryBuilder.AppendQuery(valueModificationQuery.ToInsertStatement(Name));
}
}
}
/// <summary>
/// Generates an table sync statement for this table.
/// </summary>
/// <param name="context">The request context.</param>
/// <param name="bulkContext"></param>
/// <param name="records"></param>
protected override void DoToSyncStatement(IMansionContext context, BulkOperationContext bulkContext, List<Record> records)
{
// loop through all the properties
foreach (var propertyName in Columns.Select(column => column.PropertyName))
{
// loop through all the nodes
var currentPropertyName = propertyName;
foreach (var record in records)
{
// start by cleaning up the table
var currentRecord = record;
bulkContext.Add(command =>
{
command.CommandType = CommandType.Text;
command.CommandText = string.Format("DELETE FROM [{0}] WHERE [id] = {1} AND [name] = '{2}'", Name, currentRecord.Id, currentPropertyName);
});
// check if there are any properties
var values = record.Get(context, currentPropertyName, string.Empty).Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();
if (values.Length == 0)
continue;
// create the command
bulkContext.Add(command =>
{
command.CommandType = CommandType.Text;
var nameColumnValue = command.AddParameter(currentPropertyName);
// loop through each value and write an insert statement
var buffer = new StringBuilder();
foreach (var value in values)
buffer.AppendFormat("INSERT INTO [{0}] ([id], [name], [value]) VALUES ({1}, @{2}, @{3});", Name, currentRecord.Id, nameColumnValue, command.AddParameter(value));
command.CommandText = buffer.ToString();
});
}
}
}
#endregion
#region Helper Methods
/// <summary>
/// Gets the current values of this table.
/// </summary>
/// <param name="command"></param>
/// <param name="record"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
private IEnumerable<string> GetCurrentValues(IDbCommand command, Record record, string propertyName)
{
using (var selectCommand = command.Connection.CreateCommand())
{
// create the name parameter
var nameParameter = command.CreateParameter();
nameParameter.ParameterName = "name";
nameParameter.DbType = DbType.String;
nameParameter.Value = propertyName;
nameParameter.Direction = ParameterDirection.Input;
selectCommand.Parameters.Add(nameParameter);
// assemble the command
selectCommand.CommandType = CommandType.Text;
selectCommand.CommandText = string.Format("SELECT [value] FROM [{0}] WHERE [id] = '{1}' AND [name] = @{2}", Name, record.Id, nameParameter.ParameterName);
selectCommand.Transaction = command.Transaction;
using (var reader = selectCommand.ExecuteReader())
{
if (reader == null)
throw new InvalidOperationException("Something terrible happened");
while (reader.Read())
yield return reader.GetValue(0).ToString();
}
}
}
#endregion
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.DownloadMultipleFilesJS
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Copyright (c) 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.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.ProjectManagement;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
private partial class Editor
{
private readonly TService _service;
private TargetProjectChangeInLanguage _targetProjectChangeInLanguage = TargetProjectChangeInLanguage.NoChange;
private IGenerateTypeService _targetLanguageService;
private readonly SemanticDocument _document;
private readonly State _state;
private readonly bool _intoNamespace;
private readonly bool _inNewFile;
private readonly bool _fromDialog;
private readonly GenerateTypeOptionsResult _generateTypeOptionsResult;
private readonly CancellationToken _cancellationToken;
public Editor(
TService service,
SemanticDocument document,
State state,
bool intoNamespace,
bool inNewFile,
CancellationToken cancellationToken)
{
_service = service;
_document = document;
_state = state;
_intoNamespace = intoNamespace;
_inNewFile = inNewFile;
_cancellationToken = cancellationToken;
}
public Editor(
TService service,
SemanticDocument document,
State state,
bool fromDialog,
GenerateTypeOptionsResult generateTypeOptionsResult,
CancellationToken cancellationToken)
{
_service = service;
_document = document;
_state = state;
_fromDialog = fromDialog;
_generateTypeOptionsResult = generateTypeOptionsResult;
_cancellationToken = cancellationToken;
}
private enum TargetProjectChangeInLanguage
{
NoChange,
CSharpToVisualBasic,
VisualBasicToCSharp
}
internal async Task<IEnumerable<CodeActionOperation>> GetOperationsAsync()
{
// Check to see if it is from GFU Dialog
if (!_fromDialog)
{
// Generate the actual type declaration.
var namedType = GenerateNamedType();
if (_intoNamespace)
{
if (_inNewFile)
{
// Generating into a new file is somewhat complicated.
var documentName = GetTypeName(_state) + _service.DefaultFileExtension;
return await GetGenerateInNewFileOperationsAsync(
namedType,
documentName,
null,
true,
null,
_document.Project,
_document.Project,
isDialog: false).ConfigureAwait(false);
}
else
{
return await GetGenerateIntoContainingNamespaceOperationsAsync(namedType).ConfigureAwait(false);
}
}
else
{
return await GetGenerateIntoTypeOperationsAsync(namedType).ConfigureAwait(false);
}
}
else
{
var namedType = GenerateNamedType(_generateTypeOptionsResult);
// Honor the options from the dialog
// Check to see if the type is requested to be generated in cross language Project
// e.g.: C# -> VB or VB -> C#
if (_document.Project.Language != _generateTypeOptionsResult.Project.Language)
{
_targetProjectChangeInLanguage =
_generateTypeOptionsResult.Project.Language == LanguageNames.CSharp
? TargetProjectChangeInLanguage.VisualBasicToCSharp
: TargetProjectChangeInLanguage.CSharpToVisualBasic;
// Get the cross language service
_targetLanguageService = _generateTypeOptionsResult.Project.LanguageServices.GetService<IGenerateTypeService>();
}
if (_generateTypeOptionsResult.IsNewFile)
{
return await GetGenerateInNewFileOperationsAsync(
namedType,
_generateTypeOptionsResult.NewFileName,
_generateTypeOptionsResult.Folders,
_generateTypeOptionsResult.AreFoldersValidIdentifiers,
_generateTypeOptionsResult.FullFilePath,
_generateTypeOptionsResult.Project,
_document.Project,
isDialog: true).ConfigureAwait(false);
}
else
{
return await GetGenerateIntoExistingDocumentAsync(
namedType,
_document.Project,
_generateTypeOptionsResult,
isDialog: true).ConfigureAwait(false);
}
}
}
private string GetNamespaceToGenerateInto()
{
var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim();
var rootNamespace = _service.GetRootNamespace(_document.SemanticModel.Compilation.Options).Trim();
if (!string.IsNullOrWhiteSpace(rootNamespace))
{
if (namespaceToGenerateInto == rootNamespace ||
namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal))
{
namespaceToGenerateInto = namespaceToGenerateInto.Substring(rootNamespace.Length);
}
}
return namespaceToGenerateInto;
}
private string GetNamespaceToGenerateIntoForUsageWithNamespace(Project targetProject, Project triggeringProject)
{
var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim();
if (targetProject.Language == LanguageNames.CSharp ||
targetProject == triggeringProject)
{
// If the target project is C# project then we don't have to make any modification to the namespace
// or
// This is a VB project generation into itself which requires no change as well
return namespaceToGenerateInto;
}
// If the target Project is VB then we have to check if the RootNamespace of the VB project is the parent most namespace of the type being generated
// True, Remove the RootNamespace
// False, Add Global to the Namespace
Contract.Assert(targetProject.Language == LanguageNames.VisualBasic);
IGenerateTypeService targetLanguageService = null;
if (_document.Project.Language == LanguageNames.VisualBasic)
{
targetLanguageService = _service;
}
else
{
Debug.Assert(_targetLanguageService != null);
targetLanguageService = _targetLanguageService;
}
var rootNamespace = targetLanguageService.GetRootNamespace(targetProject.CompilationOptions).Trim();
if (!string.IsNullOrWhiteSpace(rootNamespace))
{
var rootNamespaceLength = CheckIfRootNamespacePresentInNamespace(namespaceToGenerateInto, rootNamespace);
if (rootNamespaceLength > -1)
{
// True, Remove the RootNamespace
namespaceToGenerateInto = namespaceToGenerateInto.Substring(rootNamespaceLength);
}
else
{
// False, Add Global to the Namespace
namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto);
}
}
else
{
// False, Add Global to the Namespace
namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto);
}
return namespaceToGenerateInto;
}
private string AddGlobalDotToTheNamespace(string namespaceToBeGenerated)
{
return "Global." + namespaceToBeGenerated;
}
// Returns the length of the meaningful rootNamespace substring part of namespaceToGenerateInto
private int CheckIfRootNamespacePresentInNamespace(string namespaceToGenerateInto, string rootNamespace)
{
if (namespaceToGenerateInto == rootNamespace)
{
return rootNamespace.Length;
}
if (namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal))
{
return rootNamespace.Length + 1;
}
return -1;
}
private void AddFoldersToNamespaceContainers(List<string> container, IList<string> folders)
{
// Add the folder as part of the namespace if there are not empty
if (folders != null && folders.Count != 0)
{
// Remove the empty entries and replace the spaces in the folder name to '_'
var refinedFolders = folders.Where(n => n != null && !n.IsEmpty()).Select(n => n.Replace(' ', '_')).ToArray();
container.AddRange(refinedFolders);
}
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateInNewFileOperationsAsync(
INamedTypeSymbol namedType,
string documentName,
IList<string> folders,
bool areFoldersValidIdentifiers,
string fullFilePath,
Project projectToBeUpdated,
Project triggeringProject,
bool isDialog)
{
// First, we fork the solution with a new, empty, file in it.
var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, debugName: documentName);
var newSolution = projectToBeUpdated.Solution.AddDocument(newDocumentId, documentName, string.Empty, folders, fullFilePath);
// Now we get the semantic model for that file we just added. We do that to get the
// root namespace in that new document, along with location for that new namespace.
// That way, when we use the code gen service we can say "add this symbol to the
// root namespace" and it will pick the one in the new file.
var newDocument = newSolution.GetDocument(newDocumentId);
var newSemanticModel = await newDocument.GetSemanticModelAsync(_cancellationToken).ConfigureAwait(false);
var enclosingNamespace = newSemanticModel.GetEnclosingNamespace(0, _cancellationToken);
var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(
isDialog, folders, areFoldersValidIdentifiers, projectToBeUpdated, triggeringProject);
var containers = namespaceContainersAndUsings.containers;
var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport;
var rootNamespaceOrType = namedType.GenerateRootNamespaceOrType(containers);
// Now, actually ask the code gen service to add this namespace or type to the root
// namespace in the new file. This will properly generate the code, and add any
// additional niceties like imports/usings.
var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
newSolution,
enclosingNamespace,
rootNamespaceOrType,
new CodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan())),
_cancellationToken).ConfigureAwait(false);
// containers is determined to be
// 1: folders -> if triggered from Dialog
// 2: containers -> if triggered not from a Dialog but from QualifiedName
// 3: triggering document folder structure -> if triggered not from a Dialog and a SimpleName
var adjustedContainer = isDialog
? folders
: _state.SimpleName != _state.NameOrMemberAccessExpression
? containers.ToList()
: _document.Document.Folders.ToList();
// Now, take the code that would be generated and actually create an edit that would
// produce a document with that code in it.
var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
if (newDocument.Project.Language == _document.Document.Project.Language)
{
var syntaxFacts = _document.Document.GetLanguageService<ISyntaxFactsService>();
var fileBanner = syntaxFacts.GetFileBanner(_document.Root);
newRoot = newRoot.WithPrependedLeadingTrivia(fileBanner);
}
return await CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync(
projectToBeUpdated,
triggeringProject,
documentName,
newRoot,
_document.Document,
includeUsingsOrImports,
adjustedContainer,
SourceCodeKind.Regular,
_cancellationToken).ConfigureAwait(false);
}
private async Task<IEnumerable<CodeActionOperation>> CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync(
Project projectToBeUpdated,
Project triggeringProject,
string documentName,
SyntaxNode root,
Document generatingDocument,
string includeUsingsOrImports,
IList<string> containers,
SourceCodeKind sourceCodeKind,
CancellationToken cancellationToken)
{
// TODO(cyrusn): make sure documentId is unique.
var documentId = DocumentId.CreateNewId(projectToBeUpdated.Id, documentName);
var updatedSolution = projectToBeUpdated.Solution.AddDocument(DocumentInfo.Create(
documentId,
documentName,
containers,
sourceCodeKind));
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity);
// Update the Generating Document with a using if required
if (includeUsingsOrImports != null)
{
updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(updatedSolution, null, _document.Document, _state.SimpleName, includeUsingsOrImports, cancellationToken).ConfigureAwait(false);
}
// Add reference of the updated project to the triggering Project if they are 2 different projects
updatedSolution = AddProjectReference(projectToBeUpdated, triggeringProject, updatedSolution);
return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution), new OpenDocumentOperation(documentId) };
}
private static Solution AddProjectReference(Project projectToBeUpdated, Project triggeringProject, Solution updatedSolution)
{
if (projectToBeUpdated != triggeringProject)
{
if (!triggeringProject.ProjectReferences.Any(pr => pr.ProjectId == projectToBeUpdated.Id))
{
updatedSolution = updatedSolution.AddProjectReference(triggeringProject.Id, new ProjectReference(projectToBeUpdated.Id));
}
}
return updatedSolution;
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoContainingNamespaceOperationsAsync(INamedTypeSymbol namedType)
{
var enclosingNamespace = _document.SemanticModel.GetEnclosingNamespace(
_state.SimpleName.SpanStart, _cancellationToken);
var solution = _document.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync(
solution,
enclosingNamespace,
namedType,
new CodeGenerationOptions(afterThisLocation: _document.SyntaxTree.GetLocation(_state.SimpleName.Span)),
_cancellationToken)
.ConfigureAwait(false);
return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) };
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoExistingDocumentAsync(
INamedTypeSymbol namedType,
Project triggeringProject,
GenerateTypeOptionsResult generateTypeOptionsResult,
bool isDialog)
{
var root = await generateTypeOptionsResult.ExistingDocument.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var folders = generateTypeOptionsResult.ExistingDocument.Folders;
var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(isDialog, new List<string>(folders), generateTypeOptionsResult.AreFoldersValidIdentifiers, generateTypeOptionsResult.Project, triggeringProject);
var containers = namespaceContainersAndUsings.Item1;
var includeUsingsOrImports = namespaceContainersAndUsings.Item2;
Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location> enclosingNamespaceGeneratedTypeToAddAndLocation = null;
if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange)
{
enclosingNamespaceGeneratedTypeToAddAndLocation = await _service.GetOrGenerateEnclosingNamespaceSymbolAsync(
namedType,
containers,
generateTypeOptionsResult.ExistingDocument,
root,
_cancellationToken).ConfigureAwait(false);
}
else
{
enclosingNamespaceGeneratedTypeToAddAndLocation = await _targetLanguageService.GetOrGenerateEnclosingNamespaceSymbolAsync(
namedType,
containers,
generateTypeOptionsResult.ExistingDocument,
root,
_cancellationToken).ConfigureAwait(false);
}
var solution = _document.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
solution,
enclosingNamespaceGeneratedTypeToAddAndLocation.Item1,
enclosingNamespaceGeneratedTypeToAddAndLocation.Item2,
new CodeGenerationOptions(afterThisLocation: enclosingNamespaceGeneratedTypeToAddAndLocation.Item3),
_cancellationToken)
.ConfigureAwait(false);
var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var updatedSolution = solution.WithDocumentSyntaxRoot(generateTypeOptionsResult.ExistingDocument.Id, newRoot, PreservationMode.PreserveIdentity);
// Update the Generating Document with a using if required
if (includeUsingsOrImports != null)
{
updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(
updatedSolution,
generateTypeOptionsResult.ExistingDocument.Id == _document.Document.Id ? newRoot : null,
_document.Document,
_state.SimpleName,
includeUsingsOrImports,
_cancellationToken).ConfigureAwait(false);
}
updatedSolution = AddProjectReference(generateTypeOptionsResult.Project, triggeringProject, updatedSolution);
return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution) };
}
private (string[] containers, string usingOrImport) GetNamespaceContainersAndAddUsingsOrImport(
bool isDialog,
IList<string> folders,
bool areFoldersValidIdentifiers,
Project targetProject,
Project triggeringProject)
{
string includeUsingsOrImports = null;
if (!areFoldersValidIdentifiers)
{
folders = SpecializedCollections.EmptyList<string>();
}
// Now actually create the symbol that we want to add to the root namespace. The
// symbol may either be a named type (if we're not generating into a namespace) or
// it may be a namespace symbol.
string[] containers = null;
if (!isDialog)
{
// Not generated from the Dialog
containers = GetNamespaceToGenerateInto().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
}
else if (!_service.IsSimpleName(_state.NameOrMemberAccessExpression))
{
// If the usage was with a namespace
containers = GetNamespaceToGenerateIntoForUsageWithNamespace(targetProject, triggeringProject).Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
}
else
{
// Generated from the Dialog
var containerList = new List<string>();
var rootNamespaceOfTheProjectGeneratedInto =
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange
? _service.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim()
: _targetLanguageService.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim();
var projectManagementService = _document.Project.Solution.Workspace.Services.GetService<IProjectManagementService>();
var defaultNamespace = _generateTypeOptionsResult.DefaultNamespace;
// Case 1 : If the type is generated into the same C# project or
// Case 2 : If the type is generated from a C# project to a C# Project
// Case 3 : If the Type is generated from a VB Project to a C# Project
// Using and Namespace will be the DefaultNamespace + Folder Structure
if ((_document.Project == _generateTypeOptionsResult.Project && _document.Project.Language == LanguageNames.CSharp) ||
(_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp) ||
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.VisualBasicToCSharp)
{
if (!string.IsNullOrWhiteSpace(defaultNamespace))
{
containerList.Add(defaultNamespace);
}
// Populate the ContainerList
AddFoldersToNamespaceContainers(containerList, folders);
containers = containerList.ToArray();
includeUsingsOrImports = string.Join(".", containerList.ToArray());
}
// Case 4 : If the type is generated into the same VB project or
// Case 5 : If Type is generated from a VB Project to VB Project
// Case 6 : If Type is generated from a C# Project to VB Project
// Namespace will be Folder Structure and Import will have the RootNamespace of the project generated into as part of the Imports
if ((_document.Project == _generateTypeOptionsResult.Project && _document.Project.Language == LanguageNames.VisualBasic) ||
(_document.Project != _generateTypeOptionsResult.Project && _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.VisualBasic) ||
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.CSharpToVisualBasic)
{
// Populate the ContainerList
AddFoldersToNamespaceContainers(containerList, folders);
containers = containerList.ToArray();
includeUsingsOrImports = string.Join(".", containerList.ToArray());
if (!string.IsNullOrWhiteSpace(rootNamespaceOfTheProjectGeneratedInto))
{
includeUsingsOrImports = string.IsNullOrEmpty(includeUsingsOrImports) ?
rootNamespaceOfTheProjectGeneratedInto :
rootNamespaceOfTheProjectGeneratedInto + "." + includeUsingsOrImports;
}
}
Contract.Assert(includeUsingsOrImports != null);
}
return (containers, includeUsingsOrImports);
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoTypeOperationsAsync(INamedTypeSymbol namedType)
{
var codeGenService = GetCodeGenerationService();
var solution = _document.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync(
solution,
_state.TypeToGenerateInOpt,
namedType,
new CodeGenerationOptions(contextLocation: _state.SimpleName.GetLocation()),
_cancellationToken)
.ConfigureAwait(false);
return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) };
}
private IList<ITypeSymbol> GetArgumentTypes(IList<TArgumentSyntax> argumentList)
{
var types = argumentList.Select(a => _service.DetermineArgumentType(_document.SemanticModel, a, _cancellationToken));
return types.Select(FixType).ToList();
}
private ITypeSymbol FixType(
ITypeSymbol typeSymbol)
{
var compilation = _document.SemanticModel.Compilation;
return typeSymbol.RemoveUnnamedErrorTypes(compilation);
}
private ICodeGenerationService GetCodeGenerationService()
{
var language = _state.TypeToGenerateInOpt == null
? _state.SimpleName.Language
: _state.TypeToGenerateInOpt.Language;
return _document.Project.Solution.Workspace.Services.GetLanguageServices(language).GetService<ICodeGenerationService>();
}
private bool TryFindMatchingField(
ParameterName parameterName,
ITypeSymbol parameterType,
Dictionary<string, ISymbol> parameterToFieldMap,
bool caseSensitive)
{
// If the base types have an accessible field or property with the same name and
// an acceptable type, then we should just defer to that.
if (_state.BaseTypeOrInterfaceOpt != null)
{
var comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
var query =
_state.BaseTypeOrInterfaceOpt
.GetBaseTypesAndThis()
.SelectMany(t => t.GetMembers())
.Where(s => s.Name.Equals(parameterName.NameBasedOnArgument, comparison));
var symbol = query.FirstOrDefault(IsSymbolAccessible);
if (IsViableFieldOrProperty(parameterType, symbol))
{
parameterToFieldMap[parameterName.BestNameForParameter] = symbol;
return true;
}
}
return false;
}
private bool IsViableFieldOrProperty(
ITypeSymbol parameterType,
ISymbol symbol)
{
if (symbol != null && !symbol.IsStatic && parameterType.Language == symbol.Language)
{
if (symbol is IFieldSymbol field)
{
return
!field.IsReadOnly &&
_service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type);
}
else if (symbol is IPropertySymbol property)
{
return
property.Parameters.Length == 0 &&
property.SetMethod != null &&
IsSymbolAccessible(property.SetMethod) &&
_service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type);
}
}
return false;
}
private bool IsSymbolAccessible(ISymbol symbol)
{
// Public and protected constructors are accessible. Internal constructors are
// accessible if we have friend access. We can't call the normal accessibility
// checkers since they will think that a protected constructor isn't accessible
// (since we don't have the destination type that would have access to them yet).
switch (symbol.DeclaredAccessibility)
{
case Accessibility.ProtectedOrInternal:
case Accessibility.Protected:
case Accessibility.Public:
return true;
case Accessibility.ProtectedAndInternal:
case Accessibility.Internal:
// TODO: Code coverage
return _document.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(
symbol.ContainingAssembly);
default:
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.Globalization;
using System.Runtime.InteropServices;
#if !FEATURE_SLJ_PROJECTION_COMPAT
#pragma warning disable 436 // Redefining types from Windows.Foundation
#endif // !FEATURE_SLJ_PROJECTION_COMPAT
#if FEATURE_SLJ_PROJECTION_COMPAT
namespace System.Windows
#else // !FEATURE_SLJ_PROJECTION_COMPAT
namespace Windows.Foundation
#endif // FEATURE_SLJ_PROJECTION_COMPAT
{
//
// Rect is the managed projection of Windows.Foundation.Rect. Any changes to the layout
// of this type must be exactly mirrored on the native WinRT side as well.
//
// Note that this type is owned by the Jupiter team. Please contact them before making any
// changes here.
//
[StructLayout(LayoutKind.Sequential)]
public struct Rect : IFormattable
{
private float _x;
private float _y;
private float _width;
private float _height;
private const double EmptyX = Double.PositiveInfinity;
private const double EmptyY = Double.PositiveInfinity;
private const double EmptyWidth = Double.NegativeInfinity;
private const double EmptyHeight = Double.NegativeInfinity;
private readonly static Rect s_empty = CreateEmptyRect();
public Rect(double x,
double y,
double width,
double height)
{
if (width < 0)
throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum);
if (height < 0)
throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum);
_x = (float)x;
_y = (float)y;
_width = (float)width;
_height = (float)height;
}
public Rect(Point point1,
Point point2)
{
_x = (float)Math.Min(point1.X, point2.X);
_y = (float)Math.Min(point1.Y, point2.Y);
_width = (float)Math.Max(Math.Max(point1.X, point2.X) - _x, 0);
_height = (float)Math.Max(Math.Max(point1.Y, point2.Y) - _y, 0);
}
public Rect(Point location, Size size)
{
if (size.IsEmpty)
{
this = s_empty;
}
else
{
_x = (float)location.X;
_y = (float)location.Y;
_width = (float)size.Width;
_height = (float)size.Height;
}
}
internal static Rect Create(double x,
double y,
double width,
double height)
{
if (x == EmptyX && y == EmptyY && width == EmptyWidth && height == EmptyHeight)
{
return Rect.Empty;
}
else
{
return new Rect(x, y, width, height);
}
}
public double X
{
get { return _x; }
set { _x = (float)value; }
}
public double Y
{
get { return _y; }
set { _y = (float)value; }
}
public double Width
{
get { return _width; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum);
_width = (float)value;
}
}
public double Height
{
get { return _height; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum);
_height = (float)value;
}
}
public double Left
{
get { return _x; }
}
public double Top
{
get { return _y; }
}
public double Right
{
get
{
if (IsEmpty)
{
return Double.NegativeInfinity;
}
return _x + _width;
}
}
public double Bottom
{
get
{
if (IsEmpty)
{
return Double.NegativeInfinity;
}
return _y + _height;
}
}
public static Rect Empty
{
get { return s_empty; }
}
public bool IsEmpty
{
get { return _width < 0; }
}
public bool Contains(Point point)
{
return ContainsInternal(point.X, point.Y);
}
public void Intersect(Rect rect)
{
if (!this.IntersectsWith(rect))
{
this = s_empty;
}
else
{
double left = Math.Max(X, rect.X);
double top = Math.Max(Y, rect.Y);
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0);
Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0);
X = left;
Y = top;
}
}
public void Union(Rect rect)
{
if (IsEmpty)
{
this = rect;
}
else if (!rect.IsEmpty)
{
double left = Math.Min(Left, rect.Left);
double top = Math.Min(Top, rect.Top);
// We need this check so that the math does not result in NaN
if ((rect.Width == Double.PositiveInfinity) || (Width == Double.PositiveInfinity))
{
Width = Double.PositiveInfinity;
}
else
{
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
double maxRight = Math.Max(Right, rect.Right);
Width = Math.Max(maxRight - left, 0);
}
// We need this check so that the math does not result in NaN
if ((rect.Height == Double.PositiveInfinity) || (Height == Double.PositiveInfinity))
{
Height = Double.PositiveInfinity;
}
else
{
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
double maxBottom = Math.Max(Bottom, rect.Bottom);
Height = Math.Max(maxBottom - top, 0);
}
X = left;
Y = top;
}
}
public void Union(Point point)
{
Union(new Rect(point, point));
}
private bool ContainsInternal(double x, double y)
{
return ((x >= X) && (x - Width <= X) &&
(y >= Y) && (y - Height <= Y));
}
internal bool IntersectsWith(Rect rect)
{
if (Width < 0 || rect.Width < 0)
{
return false;
}
return (rect.X <= X + Width) &&
(rect.X + rect.Width >= X) &&
(rect.Y <= Y + Height) &&
(rect.Y + rect.Height >= Y);
}
private static Rect CreateEmptyRect()
{
Rect rect = new Rect();
// TODO: for consistency with width/height we should change these
// to assign directly to the backing fields.
rect.X = EmptyX;
rect.Y = EmptyY;
// the width and height properties prevent assignment of
// negative numbers so assign directly to the backing fields.
rect._width = (float)EmptyWidth;
rect._height = (float)EmptyHeight;
return rect;
}
public override string ToString()
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, null /* format provider */);
}
public string ToString(IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
string IFormattable.ToString(string format, IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
internal string ConvertToString(string format, IFormatProvider provider)
{
if (IsEmpty)
{
return SR.DirectUI_Empty;
}
// Helper to get the numeric list separator for a given culture.
char separator = TokenizerHelper.GetNumericListSeparator(provider);
return String.Format(provider,
"{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}",
separator,
_x,
_y,
_width,
_height);
}
public bool Equals(Rect value)
{
return (this == value);
}
public static bool operator ==(Rect rect1, Rect rect2)
{
return rect1.X == rect2.X &&
rect1.Y == rect2.Y &&
rect1.Width == rect2.Width &&
rect1.Height == rect2.Height;
}
public static bool operator !=(Rect rect1, Rect rect2)
{
return !(rect1 == rect2);
}
public override bool Equals(object o)
{
return o is Rect && this == (Rect)o;
}
public override int GetHashCode()
{
// Perform field-by-field XOR of HashCodes
return X.GetHashCode() ^
Y.GetHashCode() ^
Width.GetHashCode() ^
Height.GetHashCode();
}
}
}
#if !FEATURE_SLJ_PROJECTION_COMPAT
#pragma warning restore 436
#endif // !FEATURE_SLJ_PROJECTION_COMPAT
| |
namespace Microsoft.Protocols.TestSuites.MS_ASPROV
{
using System.Net;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
/// <summary>
/// This scenario is designed to test the negative status of Provision command.
/// </summary>
[TestClass]
public class S03_ProvisionNegative : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
/// <summary>
/// This test case is intended to validate Status 3 of Policy element.
/// </summary>
[TestCategory("MSASPROV"), TestMethod()]
public void MSASPROV_S03_TC01_VerifyPolicyStatus3()
{
#region Call Provision command with invalid policy type.
// Assign an invalid policy type in the provision request
string invalidType = "InvalidMS-EAS-Provisioning-WBXML";
ProvisionResponse provisionResponse = this.CallProvisionCommand(string.Empty, invalidType, "1");
byte policyStatus = provisionResponse.ResponseData.Policies.Policy.Status;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R380");
// Verify MS-ASPROV requirement: MS-ASPROV_R380
// The Status of Policy element is 3, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
3,
policyStatus,
380,
@"[In Status (Policy)] Value 3 means Unknown PolicyType value.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R471");
// Verify MS-ASPROV requirement: MS-ASPROV_R471
// The Status of Policy element is 3, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
3,
policyStatus,
471,
@"[In Provision Command Errors] [The cause of status value 3 is] The client sent a policy that the server does not recognize.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R502");
// Verify MS-ASPROV requirement: MS-ASPROV_R502
// The Status of Policy element is 3, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
3,
policyStatus,
502,
@"[In Provision Command Errors] [When the scope is Policy], [the cause of status value 3 is] The client sent a policy that the server does not recognize.");
#endregion
}
/// <summary>
/// This test case is intended to validate Status 5 of Policy element.
/// </summary>
[TestCategory("MSASPROV"), TestMethod()]
public void MSASPROV_S03_TC02_VerifyPolicyStatus5()
{
#region Download the policy settings.
// Download the policy settings.
ProvisionResponse provisionResponse = this.CallProvisionCommand(string.Empty, "MS-EAS-Provisioning-WBXML", "1");
string temporaryPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey;
#endregion
#region Acknowledge the policy settings.
// Acknowledge the policy settings.
this.CallProvisionCommand(temporaryPolicyKey, "MS-EAS-Provisioning-WBXML", "1");
#endregion
#region Switch current user to the user who has custom policy settings.
// Switch to the user who has been configured with custom policy.
this.SwitchUser(this.User2Information, false);
#endregion
#region Call Provision command with out-of-date PolicyKey.
provisionResponse = this.CallProvisionCommand(temporaryPolicyKey, "MS-EAS-Provisioning-WBXML", "1");
byte policyStatus = provisionResponse.ResponseData.Policies.Policy.Status;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R475");
// Verify MS-ASPROV requirement: MS-ASPROV_R475
// The Status of Policy element is 5, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
5,
policyStatus,
475,
@"[In Provision Command Errors] [The cause of status value 5 is] The client is trying to acknowledge an out-of-date [or invalid policy].");
#endregion
#region Call Provision command with invalid PolicyKey.
provisionResponse = this.CallProvisionCommand("1234567890", "MS-EAS-Provisioning-WBXML", "1");
policyStatus = provisionResponse.ResponseData.Policies.Policy.Status;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R761");
// Verify MS-ASPROV requirement: MS-ASPROV_R761
// The Status of Policy element is 5, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
5,
policyStatus,
761,
@"[In Provision Command Errors] [The cause of status value 5 is] The client is trying to acknowledge an [out-of-date or] invalid policy.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R382");
// Verify MS-ASPROV requirement: MS-ASPROV_R382
// The Status of Policy element is 5, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
5,
policyStatus,
382,
@"[In Status (Policy)] Value 5 means The client is acknowledging the wrong policy key.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R692");
// Verify MS-ASPROV requirement: MS-ASPROV_R692
// The Status of Policy element is 5, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
5,
policyStatus,
692,
@"[In Provision Command Errors] [The meaning of status value] 5 [is] Policy key mismatch.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R507");
// Verify MS-ASPROV requirement: MS-ASPROV_R507
// The Status of Policy element is 5, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
5,
policyStatus,
507,
@"[In Provision Command Errors] [When the scope is Policy], [the cause of status value 5 is] The client is trying to acknowledge an out-of-date or invalid policy.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R708");
// Verify MS-ASPROV requirement: MS-ASPROV_R708
// The Status of Policy element is 5, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
5,
policyStatus,
708,
@"[In Provision Command Errors] [When the scope is] Policy, [the meaning of status value] 5 [is] Policy key mismatch.");
if (Common.IsRequirementEnabled(695, this.Site))
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R695");
// Verify MS-ASPROV requirement: MS-ASPROV_R695
// The Status of Policy element is 5, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
5,
policyStatus,
695,
@"[In Appendix B: Product Behavior] If it does not [current policy key sent by the client in a security policy settings acknowledgment does not match the temporary policy key issued by the server in the response to the initial request from this client], the implementation does return a Status (section 2.2.2.53.2) value of 5, as specified in section 3.2.5.2. (Exchange 2007 and above follow this behavior.)");
}
#endregion
}
/// <summary>
/// This test case is intended to validate Status 2 of Provision element.
/// </summary>
[TestCategory("MSASPROV"), TestMethod()]
public void MSASPROV_S03_TC03_VerifyProvisionStatus2()
{
#region Create a Provision request with syntax error.
ProvisionRequest provisionRequest = Common.CreateProvisionRequest(null, new Request.ProvisionPolicies(), null);
Request.ProvisionPoliciesPolicy policy = new Request.ProvisionPoliciesPolicy
{
PolicyType = "MS-EAS-Provisioning-WBXML"
};
// The format in which the policy settings are to be provided to the client device.
if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site) == "14.1" ||
Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site) == "16.0" ||
Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site) == "16.1")
{
// Configure the DeviceInformation.
Request.DeviceInformation deviceInfomation = new Request.DeviceInformation();
Request.DeviceInformationSet deviceInformationSet = new Request.DeviceInformationSet
{
Model = "ASPROVTest"
};
deviceInfomation.Set = deviceInformationSet;
provisionRequest.RequestData.DeviceInformation = deviceInfomation;
}
provisionRequest.RequestData.Policies.Policy = policy;
string requestBody = provisionRequest.GetRequestDataSerializedXML();
requestBody = requestBody.Replace(@"<Policies>", string.Empty);
requestBody = requestBody.Replace(@"</Policies>", string.Empty);
#endregion
#region Call Provision command and get the Status of response.
ProvisionResponse provisionResponse = this.PROVAdapter.SendProvisionStringRequest(requestBody);
byte provisionStatus = provisionResponse.ResponseData.Status;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R395");
// Verify MS-ASPROV requirement: MS-ASPROV_R395
// The Status of Provision element is 2, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
2,
provisionStatus,
395,
@"[In Status (Provision)] Value 2 means Protocol error.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R679");
// Verify MS-ASPROV requirement: MS-ASPROV_R679
// The Status of Provision element is 2, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
2,
provisionStatus,
679,
@"[In Provision Command Errors] [The meaning of status value] 2 [is] Protocol error.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R450");
// Verify MS-ASPROV requirement: MS-ASPROV_R450
// The Status of Provision element is 2, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
2,
provisionStatus,
450,
@"[In Provision Command Errors] [The cause of status value 2 is] Syntax error in the Provision command request.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R497");
// Verify MS-ASPROV requirement: MS-ASPROV_R497
// The Status of Provision element is 2, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<byte>(
2,
provisionStatus,
497,
@"[In Provision Command Errors] [When the scope is Global], [the cause of status value 2 is] Syntax error in the Provision command request.");
if (Common.IsRequirementEnabled(697, this.Site))
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R697");
// Verify MS-ASPROV requirement: MS-ASPROV_R697
// Status 2 is returned when there is syntax error in the Provision command request, so this requirement can be captured.
Site.CaptureRequirement(
697,
@"[In Appendix B: Product Behavior] If the level of compliance does not meet the server's requirements, the implementation does return an appropriate value in the Status (section 2.2.2.53.2) element. (Exchange 2007 and above follow this behavior.)");
}
#endregion
}
/// <summary>
/// This test case is intended to validate the status code when the policy key is invalid.
/// </summary>
[TestCategory("MSASPROV"), TestMethod()]
public void MSASPROV_S03_TC04_VerifyInvalidPolicyKey()
{
#region Call Provision command to download the policy settings.
// Download the policy setting.
ProvisionResponse provisionResponse = this.CallProvisionCommand(string.Empty, "MS-EAS-Provisioning-WBXML", "1");
string temporaryPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey;
#endregion
#region Call Provision command to acknowledge the policy settings and get the valid PolicyKey
// Acknowledge the policy setting.
provisionResponse = this.CallProvisionCommand(temporaryPolicyKey, "MS-EAS-Provisioning-WBXML", "1");
string finalPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey;
#endregion
#region Call FolderSync command with an invalid PolicyKey which is different from the one got from last step.
// Apply an invalid policy key
this.PROVAdapter.ApplyPolicyKey(finalPolicyKey.Substring(0, 1));
// Call folder sync with "0" in initialization phase.
FolderSyncRequest folderSyncRequest = Common.CreateFolderSyncRequest("0");
if ("12.1" == Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site))
{
string httpErrorCode = null;
try
{
this.PROVAdapter.FolderSync(folderSyncRequest);
}
catch (WebException exception)
{
httpErrorCode = Common.GetErrorCodeFromException(exception);
}
Site.Assert.IsFalse(string.IsNullOrEmpty(httpErrorCode), "Server should return expected [449] error code if client do not have policy key");
}
else
{
FolderSyncResponse folderSyncResponse = this.PROVAdapter.FolderSync(folderSyncRequest);
Site.Assert.AreEqual(144, int.Parse(folderSyncResponse.ResponseData.Status), "The server should return status 144 to indicate a invalid policy key.");
}
if (Common.IsRequirementEnabled(537, this.Site))
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R537");
// Verify MS-ASPROV requirement: MS-ASPROV_R537
// If the above capture or assert passed, it means the server did returns a status code when the policy key is mismatched.
Site.CaptureRequirement(
537,
@"[In Appendix B: Product Behavior] If the policy key received from the client does not match the stored policy key on the server [, or if the server determines that policy settings need to be updated on the client], the implementation does return a status code, as specified in [MS-ASCMD] section 2.2.4, in the next command response indicating that the client needs to send another Provision command to request the security policy settings and obtain a new policy key. (Exchange 2007 and above follow this behavior.)");
}
#endregion
}
/// <summary>
/// This test case is intended to validate Status 139 of Policy element.
/// </summary>
[TestCategory("MSASPROV"), TestMethod()]
public void MSASPROV_S03_TC05_VerifyPolicyStatus139()
{
#region Download the policy settings.
// Download the policy settings.
ProvisionResponse provisionResponse = this.CallProvisionCommand(string.Empty, "MS-EAS-Provisioning-WBXML", "1");
string temporaryPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey;
#endregion
#region Acknowledge the policy settings.
// Acknowledge the policy settings.
provisionResponse = this.CallProvisionCommand(temporaryPolicyKey, "MS-EAS-Provisioning-WBXML", "2");
if (Common.IsRequirementEnabled(1046, this.Site))
{
this.Site.CaptureRequirementIfAreEqual<byte>(
139,
provisionResponse.ResponseData.Status,
1046,
@"[In Appendix B: Product Behavior] [The cause of status value 139 is] The client returned a value of 2 in the Status child element of the Policy element in a request to the implementation to acknowledge a policy. (Exchange 2013 and above follow this behavior.)");
this.Site.CaptureRequirementIfAreEqual<byte>(
139,
provisionResponse.ResponseData.Status,
681,
@"[In Provision Command Errors] [The meaning of status value] 139 [is] The client cannot fully comply with all requirements of the policy.");
this.Site.CaptureRequirementIfAreEqual<byte>(
139,
provisionResponse.ResponseData.Status,
684,
@"[In Provision Command Errors] [The cause of status value 139 is] The server is configured to not allow clients that cannot fully apply the policy.");
}
#endregion
}
/// <summary>
/// This test case is intended to validate Status 145 of Policy element.
/// </summary>
[TestCategory("MSASPROV"), TestMethod()]
public void MSASPROV_S03_TC06_VerifyPolicyStatus145()
{
#region Download the policy settings.
// Download the policy settings.
ProvisionResponse provisionResponse = this.CallProvisionCommand(string.Empty, "MS-EAS-Provisioning-WBXML", "1");
string temporaryPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey;
#endregion
#region Acknowledge the policy settings.
if ("12.1" != Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site))
{
// Acknowledge the policy settings.
provisionResponse = this.CallProvisionCommand(temporaryPolicyKey, "MS-EAS-Provisioning-WBXML", "4");
this.Site.CaptureRequirementIfAreEqual<byte>(
145,
provisionResponse.ResponseData.Status,
686,
@"[In Provision Command Errors] [The meaning of status value] 145 [is] The client is externally managed.");
this.Site.CaptureRequirementIfAreEqual<byte>(
145,
provisionResponse.ResponseData.Status,
461,
@"[In Provision Command Errors] [The cause of status value 145 is] The client returned a value of 4 in the Status child element of the Policy element in a request to the server to acknowledge a policy.");
this.Site.CaptureRequirementIfAreEqual<byte>(
145,
provisionResponse.ResponseData.Status,
687,
@"[In Provision Command Errors] [The cause of status value 145 is] The server is configured to not allow externally managed clients.");
}
#endregion
}
/// <summary>
/// This test case is intended to validate the Status 141.
/// </summary>
[TestCategory("MSASPROV"), TestMethod()]
public void MSASPROV_S03_TC07_VerifyStatus141()
{
#region Call Provision command to download the policy settings.
// Download the policy setting.
ProvisionResponse provisionResponse = this.CallProvisionCommand(string.Empty, "MS-EAS-Provisioning-WBXML", "1");
string temporaryPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey;
#endregion
#region Call Provision command to acknowledge the policy settings and get the valid PolicyKey
// Acknowledge the policy setting.
provisionResponse = this.CallProvisionCommand(temporaryPolicyKey, "MS-EAS-Provisioning-WBXML", "1");
string finalPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey;
#endregion
#region Call FolderSync command with an emtry PolicyKey.
if ("12.1" != Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site))
{
// Apply an emtry policy key
this.PROVAdapter.ApplyPolicyKey(string.Empty);
// Call folder sync with "0" in initialization phase.
FolderSyncRequest folderSyncRequest = Common.CreateFolderSyncRequest("0");
FolderSyncResponse folderSyncResponse = this.PROVAdapter.FolderSync(folderSyncRequest);
this.Site.CaptureRequirementIfAreEqual<int>(
141,
int.Parse(folderSyncResponse.ResponseData.Status),
682,
@"[In Provision Command Errors] [The meaning of status value] 141 [is] The device is not provisionable.");
this.Site.CaptureRequirementIfAreEqual<int>(
141,
int.Parse(folderSyncResponse.ResponseData.Status),
458,
@"[In Provision Command Errors] [The cause of status value 141 is] The client did not submit a policy key value in a request.");
this.Site.CaptureRequirementIfAreEqual<int>(
141,
int.Parse(folderSyncResponse.ResponseData.Status),
685,
@"[In Provision Command Errors] [The cause of status value 141 is] The server is configured to not allow clients that do not submit a policy key value.");
}
#endregion
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
using PCSComUtils.MasterSetup.DS;
using PCSComMaterials.Inventory.DS;
namespace PCSComMaterials.Inventory.BO
{
public interface IIVInventoryAdjustmentBO
{
int AddAndReturnID(object pobjObject);
DataSet GetAvalableQuantity(int pintCCNID, int pintMasterLocationID, int pintLocationID, int pintBinID, int pintProductID);
}
/// <summary>
/// Summary description for IVInventoryAdjustmentBO.
/// </summary>
public class IVInventoryAdjustmentBO : IIVInventoryAdjustmentBO
{
public IVInventoryAdjustmentBO()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Insert a new record into database
/// </summary>
public void Add(object pObjectDetail)
{
throw new NotImplementedException();
}
/// <summary>
/// Delete record by condition
/// </summary>
public void Delete(object pObjectVO)
{
throw new NotImplementedException();
}
/// <summary>
/// Get the object information by ID of VO class
/// </summary>
public object GetObjectVO(int pintID, string VOclass)
{
throw new NotImplementedException();
}
/// <summary>
/// Return the DataSet (list of record) by inputing the FieldList and Condition
/// </summary>
public void UpdateDataSet(DataSet dstData)
{
throw new NotImplementedException();
}
/// <summary>
/// Update into Database
/// </summary>
public void Update(object pObjectDetail)
{
throw new NotImplementedException();
}
/// <summary>
/// AddAndReturnID
/// </summary>
/// <param name="pobjObject"></param>
/// <author>Trada</author>
/// <date>Wednesday, July 27 2005</date>
public int AddAndReturnID(object pobjObject)
{
string METHODE_NAME = "AddAndReturnID()";
IV_AdjustmentVO voIV_Adjustment = (IV_AdjustmentVO)pobjObject;
decimal decRemain = 0;
//Check Available Quantity
InventoryUtilsBO boInventoryUtils = new InventoryUtilsBO();
DateTime dtmCurrentDate = new UtilsBO().GetDBDate().AddDays(1);
if (voIV_Adjustment.AdjustQuantity < 0)
{
decRemain = boInventoryUtils.GetAvailableQtyByPostDate(dtmCurrentDate, voIV_Adjustment.CCNID, voIV_Adjustment.MasterLocationID, voIV_Adjustment.LocationID, voIV_Adjustment.BinID, voIV_Adjustment.ProductID)
+ voIV_Adjustment.AdjustQuantity;
if (decRemain < 0)
{
throw new PCSBOException(ErrorCode.MESSAGE_IV_ADJUSTMENT_ADJUSTQTY_MUST_BE_SMALLER_THAN_AVAILABLEQTY, METHODE_NAME, new Exception());
}
else
{
decimal decAvailableQty = boInventoryUtils.GetAvailableQtyByPostDate(new UtilsBO().GetDBDate(), voIV_Adjustment.CCNID, voIV_Adjustment.MasterLocationID, voIV_Adjustment.LocationID, voIV_Adjustment.BinID, voIV_Adjustment.ProductID);
if (-voIV_Adjustment.AdjustQuantity > decAvailableQty)
{
throw new PCSBOException(ErrorCode.MESSAGE_AVAILABLE_WAS_USED_AFTER_POSTDATE, METHODE_NAME, new Exception());
}
}
}
//AddAndReturnID
int pintIV_AdjustmentID;
IV_AdjustmentDS dsIV_Adjustment = new IV_AdjustmentDS();
pintIV_AdjustmentID = dsIV_Adjustment.AddAndReturnID(pobjObject);
//Update Add Onhand Quantity
boInventoryUtils.UpdateAddOHQuantity(voIV_Adjustment.CCNID, voIV_Adjustment.MasterLocationID, voIV_Adjustment.LocationID, voIV_Adjustment.BinID,
voIV_Adjustment.ProductID, voIV_Adjustment.AdjustQuantity, voIV_Adjustment.Lot, voIV_Adjustment.Serial);
//Save history to MST_TransactionHistory
MST_TransactionHistoryVO voMST_TransactionHistory = new MST_TransactionHistoryVO();
voMST_TransactionHistory.CCNID = voIV_Adjustment.CCNID;
voMST_TransactionHistory.MasterLocationID = voIV_Adjustment.MasterLocationID;
voMST_TransactionHistory.LocationID = voIV_Adjustment.LocationID;
voMST_TransactionHistory.BinID = voIV_Adjustment.BinID;
voMST_TransactionHistory.ProductID = voIV_Adjustment.ProductID;
voMST_TransactionHistory.RefMasterID = pintIV_AdjustmentID;
voMST_TransactionHistory.TranTypeID = new MST_TranTypeDS().GetTranTypeID(TransactionType.INVENTORY_ADJUSTMENT);
voMST_TransactionHistory.PostDate = voIV_Adjustment.PostDate;
voMST_TransactionHistory.TransDate = new UtilsBO().GetDBDate();
voMST_TransactionHistory.Quantity = voIV_Adjustment.AdjustQuantity;
voMST_TransactionHistory.StockUMID = voIV_Adjustment.StockUMID;
boInventoryUtils.SaveTransactionHistory(TransactionType.INVENTORY_ADJUSTMENT, (int) PurposeEnum.Adjustment, voMST_TransactionHistory);
return pintIV_AdjustmentID;
}
/// <summary>
/// GetAvalableQuantity
/// </summary>
/// <param name="pintLocationID"></param>
/// <param name="pintBinID"></param>
/// <param name="pintProductID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Monday, October 17 2005</date>
public DataSet GetAvalableQuantity(int pintCCNID, int pintMasterLocationID, int pintLocationID, int pintBinID, int pintProductID)
{
if (pintBinID == 0)
{
IV_LocationCacheDS dsIV_LocationCache = new IV_LocationCacheDS();
return dsIV_LocationCache.GetAvailableQtyAndInsStatusByProduct(pintCCNID, pintMasterLocationID, pintLocationID, pintProductID);
}
else
{
IV_BinCacheDS dsIV_BinCache = new IV_BinCacheDS();
return dsIV_BinCache.GetAvailableQtyAndInsStatusByProduct(pintCCNID, pintMasterLocationID, pintLocationID, pintBinID, pintProductID);
}
}
/// <summary>
/// DeleteInventoryAdjustment
/// </summary>
/// <param name="printInventoryAdjustmentID"></param>
/// <returns></returns>
/// <author>CanhNV</author>
/// <date>24-03-2007</date>
public void DeleteInventoryAdjustment(int printInventoryAdjustmentID)
{
// 0. Variable
IV_AdjustmentDS objAdjustmentDS = new IV_AdjustmentDS();
IV_AdjustmentVO voAdjustment = new IV_AdjustmentVO();
MST_TransactionHistoryVO voTransactionHistory = new MST_TransactionHistoryVO();
int InspStatus = 17;
// 1. Get Infomation of InventoryAdjustment
voAdjustment = (IV_AdjustmentVO) objAdjustmentDS.GetObjectVOByAdjustmentID(printInventoryAdjustmentID);
// 2. Delete InventoryAdjustment
objAdjustmentDS.DeleteByAdjustmentID(printInventoryAdjustmentID);
#region Set voTransactionHistory value
voTransactionHistory.TransDate = new UtilsBO().GetDBDate();
voTransactionHistory.TranTypeID = new MST_TranTypeDS().GetTranTypeID(TransactionType.INVENTORY_ADJUSTMENT);
voTransactionHistory.ProductID = voAdjustment.ProductID;
voTransactionHistory.CCNID = voAdjustment.CCNID;
voTransactionHistory.Lot = voAdjustment.Lot;
voTransactionHistory.StockUMID = voAdjustment.StockUMID;
voTransactionHistory.Serial = voAdjustment.Serial;
voTransactionHistory.PostDate = voAdjustment.PostDate;
voTransactionHistory.RefMasterID = voAdjustment.AdjustmentID;
voTransactionHistory.Quantity = voAdjustment.AdjustQuantity;
voTransactionHistory.MasterLocationID = voAdjustment.MasterLocationID;
voTransactionHistory.LocationID = voAdjustment.LocationID;
voTransactionHistory.BinID = voAdjustment.BinID;
#endregion
// 3. Update Inventory
new InventoryUtilsBO().UpdateSubtractOHQuantity(voAdjustment.CCNID,
voTransactionHistory.MasterLocationID,
voTransactionHistory.LocationID,
voTransactionHistory.BinID,
voTransactionHistory.ProductID,
voTransactionHistory.Quantity,
string.Empty,
string.Empty);
// 4. Update TransactionHistory
new MST_TransactionHistoryDS().UpdateTranType(voAdjustment.AdjustmentID,voTransactionHistory.TranTypeID,(int) TransactionTypeEnum.DeleteTransaction,InspStatus);
}
/// <summary>
/// DeleteInventoryAdjustmentTransaction
/// </summary>
/// <param name="printInventoryAdjustmentID"></param>
/// <returns></returns>
/// <author>CanhNV</author>
/// <date>24-03-2007</date>
public void DeleteInventoryAdjustmentTransaction(int printInventoryAdjustmentID)
{
// 0. Variable
IV_AdjustmentDS objAdjustmentDS = new IV_AdjustmentDS();
IV_AdjustmentVO voAdjustment = new IV_AdjustmentVO();
MST_TransactionHistoryVO voTransactionHistory = new MST_TransactionHistoryVO();
decimal decQuantity = 0;
int InspStatus = 172;
// 1. Get Infomation of InventoryAdjustment
voAdjustment = (IV_AdjustmentVO) objAdjustmentDS.GetObjectVOByAdjustmentID(printInventoryAdjustmentID);
// 2. Delete InventoryAdjustment
objAdjustmentDS.DeleteByAdjustmentID(printInventoryAdjustmentID);
#region Set voTransactionHistory value
voTransactionHistory.TransDate = new UtilsBO().GetDBDate();
voTransactionHistory.TranTypeID = new MST_TranTypeDS().GetTranTypeID(TransactionType.INVENTORY_ADJUSTMENT);
voTransactionHistory.ProductID = voAdjustment.ProductID;
voTransactionHistory.CCNID = voAdjustment.CCNID;
voTransactionHistory.Lot = voAdjustment.Lot;
voTransactionHistory.StockUMID = voAdjustment.StockUMID;
voTransactionHistory.Serial = voAdjustment.Serial;
voTransactionHistory.PostDate = voAdjustment.PostDate;
voTransactionHistory.RefMasterID = voAdjustment.AdjustmentID;
voTransactionHistory.Quantity = voAdjustment.AdjustQuantity;
voTransactionHistory.MasterLocationID = voAdjustment.MasterLocationID;
voTransactionHistory.LocationID = voAdjustment.LocationID;
voTransactionHistory.BinID = voAdjustment.BinID;
#endregion
// 3. Update TransactionHistory
new MST_TransactionHistoryDS().UpdateTranType(voAdjustment.AdjustmentID,voTransactionHistory.TranTypeID,(int) TransactionTypeEnum.DeleteTransaction,InspStatus);
}
}
}
| |
using System;
using System.Collections;
using ChainUtils.BouncyCastle.Utilities;
using ChainUtils.BouncyCastle.Utilities.Collections;
namespace ChainUtils.BouncyCastle.Asn1.X509
{
public class X509Extensions
: Asn1Encodable
{
/**
* Subject Directory Attributes
*/
public static readonly DerObjectIdentifier SubjectDirectoryAttributes = new DerObjectIdentifier("2.5.29.9");
/**
* Subject Key Identifier
*/
public static readonly DerObjectIdentifier SubjectKeyIdentifier = new DerObjectIdentifier("2.5.29.14");
/**
* Key Usage
*/
public static readonly DerObjectIdentifier KeyUsage = new DerObjectIdentifier("2.5.29.15");
/**
* Private Key Usage Period
*/
public static readonly DerObjectIdentifier PrivateKeyUsagePeriod = new DerObjectIdentifier("2.5.29.16");
/**
* Subject Alternative Name
*/
public static readonly DerObjectIdentifier SubjectAlternativeName = new DerObjectIdentifier("2.5.29.17");
/**
* Issuer Alternative Name
*/
public static readonly DerObjectIdentifier IssuerAlternativeName = new DerObjectIdentifier("2.5.29.18");
/**
* Basic Constraints
*/
public static readonly DerObjectIdentifier BasicConstraints = new DerObjectIdentifier("2.5.29.19");
/**
* CRL Number
*/
public static readonly DerObjectIdentifier CrlNumber = new DerObjectIdentifier("2.5.29.20");
/**
* Reason code
*/
public static readonly DerObjectIdentifier ReasonCode = new DerObjectIdentifier("2.5.29.21");
/**
* Hold Instruction Code
*/
public static readonly DerObjectIdentifier InstructionCode = new DerObjectIdentifier("2.5.29.23");
/**
* Invalidity Date
*/
public static readonly DerObjectIdentifier InvalidityDate = new DerObjectIdentifier("2.5.29.24");
/**
* Delta CRL indicator
*/
public static readonly DerObjectIdentifier DeltaCrlIndicator = new DerObjectIdentifier("2.5.29.27");
/**
* Issuing Distribution Point
*/
public static readonly DerObjectIdentifier IssuingDistributionPoint = new DerObjectIdentifier("2.5.29.28");
/**
* Certificate Issuer
*/
public static readonly DerObjectIdentifier CertificateIssuer = new DerObjectIdentifier("2.5.29.29");
/**
* Name Constraints
*/
public static readonly DerObjectIdentifier NameConstraints = new DerObjectIdentifier("2.5.29.30");
/**
* CRL Distribution Points
*/
public static readonly DerObjectIdentifier CrlDistributionPoints = new DerObjectIdentifier("2.5.29.31");
/**
* Certificate Policies
*/
public static readonly DerObjectIdentifier CertificatePolicies = new DerObjectIdentifier("2.5.29.32");
/**
* Policy Mappings
*/
public static readonly DerObjectIdentifier PolicyMappings = new DerObjectIdentifier("2.5.29.33");
/**
* Authority Key Identifier
*/
public static readonly DerObjectIdentifier AuthorityKeyIdentifier = new DerObjectIdentifier("2.5.29.35");
/**
* Policy Constraints
*/
public static readonly DerObjectIdentifier PolicyConstraints = new DerObjectIdentifier("2.5.29.36");
/**
* Extended Key Usage
*/
public static readonly DerObjectIdentifier ExtendedKeyUsage = new DerObjectIdentifier("2.5.29.37");
/**
* Freshest CRL
*/
public static readonly DerObjectIdentifier FreshestCrl = new DerObjectIdentifier("2.5.29.46");
/**
* Inhibit Any Policy
*/
public static readonly DerObjectIdentifier InhibitAnyPolicy = new DerObjectIdentifier("2.5.29.54");
/**
* Authority Info Access
*/
public static readonly DerObjectIdentifier AuthorityInfoAccess = new DerObjectIdentifier("1.3.6.1.5.5.7.1.1");
/**
* Subject Info Access
*/
public static readonly DerObjectIdentifier SubjectInfoAccess = new DerObjectIdentifier("1.3.6.1.5.5.7.1.11");
/**
* Logo Type
*/
public static readonly DerObjectIdentifier LogoType = new DerObjectIdentifier("1.3.6.1.5.5.7.1.12");
/**
* BiometricInfo
*/
public static readonly DerObjectIdentifier BiometricInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.1.2");
/**
* QCStatements
*/
public static readonly DerObjectIdentifier QCStatements = new DerObjectIdentifier("1.3.6.1.5.5.7.1.3");
/**
* Audit identity extension in attribute certificates.
*/
public static readonly DerObjectIdentifier AuditIdentity = new DerObjectIdentifier("1.3.6.1.5.5.7.1.4");
/**
* NoRevAvail extension in attribute certificates.
*/
public static readonly DerObjectIdentifier NoRevAvail = new DerObjectIdentifier("2.5.29.56");
/**
* TargetInformation extension in attribute certificates.
*/
public static readonly DerObjectIdentifier TargetInformation = new DerObjectIdentifier("2.5.29.55");
private readonly IDictionary extensions = Platform.CreateHashtable();
private readonly IList ordering;
public static X509Extensions GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
}
public static X509Extensions GetInstance(
object obj)
{
if (obj == null || obj is X509Extensions)
{
return (X509Extensions) obj;
}
if (obj is Asn1Sequence)
{
return new X509Extensions((Asn1Sequence) obj);
}
if (obj is Asn1TaggedObject)
{
return GetInstance(((Asn1TaggedObject) obj).GetObject());
}
throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
}
/**
* Constructor from Asn1Sequence.
*
* the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString)
*/
private X509Extensions(
Asn1Sequence seq)
{
ordering = Platform.CreateArrayList();
foreach (Asn1Encodable ae in seq)
{
var s = Asn1Sequence.GetInstance(ae.ToAsn1Object());
if (s.Count < 2 || s.Count > 3)
throw new ArgumentException("Bad sequence size: " + s.Count);
var oid = DerObjectIdentifier.GetInstance(s[0].ToAsn1Object());
var isCritical = s.Count == 3
&& DerBoolean.GetInstance(s[1].ToAsn1Object()).IsTrue;
var octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object());
extensions.Add(oid, new X509Extension(isCritical, octets));
ordering.Add(oid);
}
}
/**
* constructor from a table of extensions.
* <p>
* it's is assumed the table contains Oid/string pairs.</p>
*/
public X509Extensions(
IDictionary extensions)
: this(null, extensions)
{
}
/**
* Constructor from a table of extensions with ordering.
* <p>
* It's is assumed the table contains Oid/string pairs.</p>
*/
public X509Extensions(
IList ordering,
IDictionary extensions)
{
if (ordering == null)
{
this.ordering = Platform.CreateArrayList(extensions.Keys);
}
else
{
this.ordering = Platform.CreateArrayList(ordering);
}
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension)extensions[oid]);
}
}
/**
* Constructor from two vectors
*
* @param objectIDs an ArrayList of the object identifiers.
* @param values an ArrayList of the extension values.
*/
public X509Extensions(
IList oids,
IList values)
{
ordering = Platform.CreateArrayList(oids);
var count = 0;
foreach (DerObjectIdentifier oid in ordering)
{
extensions.Add(oid, (X509Extension)values[count++]);
}
}
#if !SILVERLIGHT
/**
* constructor from a table of extensions.
* <p>
* it's is assumed the table contains Oid/string pairs.</p>
*/
[Obsolete]
public X509Extensions(
Hashtable extensions)
: this(null, extensions)
{
}
/**
* Constructor from a table of extensions with ordering.
* <p>
* It's is assumed the table contains Oid/string pairs.</p>
*/
[Obsolete]
public X509Extensions(
ArrayList ordering,
Hashtable extensions)
{
if (ordering == null)
{
this.ordering = Platform.CreateArrayList(extensions.Keys);
}
else
{
this.ordering = Platform.CreateArrayList(ordering);
}
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension) extensions[oid]);
}
}
/**
* Constructor from two vectors
*
* @param objectIDs an ArrayList of the object identifiers.
* @param values an ArrayList of the extension values.
*/
[Obsolete]
public X509Extensions(
ArrayList oids,
ArrayList values)
{
this.ordering = Platform.CreateArrayList(oids);
int count = 0;
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension) values[count++]);
}
}
#endif
[Obsolete("Use ExtensionOids IEnumerable property")]
public IEnumerator Oids()
{
return ExtensionOids.GetEnumerator();
}
/**
* return an Enumeration of the extension field's object ids.
*/
public IEnumerable ExtensionOids
{
get { return new EnumerableProxy(ordering); }
}
/**
* return the extension represented by the object identifier
* passed in.
*
* @return the extension if it's present, null otherwise.
*/
public X509Extension GetExtension(
DerObjectIdentifier oid)
{
return (X509Extension) extensions[oid];
}
/**
* <pre>
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Extension ::= SEQUENCE {
* extnId EXTENSION.&id ({ExtensionSet}),
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
* </pre>
*/
public override Asn1Object ToAsn1Object()
{
var vec = new Asn1EncodableVector();
foreach (DerObjectIdentifier oid in ordering)
{
var ext = (X509Extension) extensions[oid];
var v = new Asn1EncodableVector(oid);
if (ext.IsCritical)
{
v.Add(DerBoolean.True);
}
v.Add(ext.Value);
vec.Add(new DerSequence(v));
}
return new DerSequence(vec);
}
public bool Equivalent(
X509Extensions other)
{
if (extensions.Count != other.extensions.Count)
return false;
foreach (DerObjectIdentifier oid in extensions.Keys)
{
if (!extensions[oid].Equals(other.extensions[oid]))
return false;
}
return true;
}
public DerObjectIdentifier[] GetExtensionOids()
{
return ToOidArray(ordering);
}
public DerObjectIdentifier[] GetNonCriticalExtensionOids()
{
return GetExtensionOids(false);
}
public DerObjectIdentifier[] GetCriticalExtensionOids()
{
return GetExtensionOids(true);
}
private DerObjectIdentifier[] GetExtensionOids(bool isCritical)
{
var oids = Platform.CreateArrayList();
foreach (DerObjectIdentifier oid in ordering)
{
var ext = (X509Extension)extensions[oid];
if (ext.IsCritical == isCritical)
{
oids.Add(oid);
}
}
return ToOidArray(oids);
}
private static DerObjectIdentifier[] ToOidArray(IList oids)
{
var oidArray = new DerObjectIdentifier[oids.Count];
oids.CopyTo(oidArray, 0);
return oidArray;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace SmartLMS.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// System
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Discord
using Discord;
using Discord.API;
using Discord.Audio;
using Discord.Commands;
using Discord.Logging;
using Discord.Net;
using Discord.OAuth2;
// Newtonsoft
using Newtonsoft.Json;
// SucyDiscordBot
using SucyDiscordBot.src.scripts.modules;
namespace SucyDiscordBot.src.scripts {
// Target Class
class Target {
public string Token { get; set; }
public ulong OwnerId { get; set; }
public Boolean Configured { get; set; }
public string Prefix { get; set; }
public string GoogleAPIKey { get; set; }
public string SoundCloudClientID { get; set; }
}
// MasterScript Class
class MasterScript {
// variables
DiscordClient client;
ConsoleScript conscr;
CommandService commands;
string json1;
bool bcfgChanged = false;
Target newTarget1;
// constructor
public MasterScript(ConsoleScript cosc) {
conscr = cosc;
try {
// finding json file
json1 = File.ReadAllText("bot_config.json");
newTarget1 = JsonConvert.DeserializeObject<Target>(json1);
// checking stuff
conscr.Print("Normal","Checking configuration file...");
conscr.Wait(3);
configReader();
checkAPIKeys();
string output = JsonConvert.SerializeObject(newTarget1,Formatting.Indented);
// Console.WriteLine(output); // this was mainly used as a debugger
if (bcfgChanged == true) File.WriteAllText("bot_config.json", output);
// initializing client functions
client = new DiscordClient(input => {
input.LogLevel = LogSeverity.Info;
input.LogHandler = Log;
});
client.UsingCommands(input => {
input.PrefixChar = '>';
input.AllowMentionPrefix = false;
});
client.UsingAudio(x => {
x.Mode = AudioMode.Outgoing;
});
// initializing other compontents
client.UserJoined += async (s, e) => {
conscr.Print("Warning", $"[Event] {e.User.Name} has joined the server.");
conscr.Print("Warning", $"{e.User.Mention}.");
var channel = e.Server.FindChannels("general", ChannelType.Text).FirstOrDefault();
await channel.SendMessage($"{e.User.Mention} has joined the server!");
};
client.UserLeft += async (s, e) => {
conscr.Print("Warning", $"[Event] {e.User.Name} has left the server.");
var channel = e.Server.FindChannels("general",ChannelType.Text).FirstOrDefault();
await channel.SendMessage($"{e.User.Name} has left the server... :c");
};
client.UserBanned += async (s, e) => {
conscr.Print("Error", $"[Event] {e.User.Name} has been banned from the server!");
var channel = e.Server.FindChannels("general", ChannelType.Text).FirstOrDefault();
await channel.SendMessage($"{e.User.Name} has been banned from the server! :O");
};
client.UserUnbanned += async (s, e) => {
conscr.Print("Error", $"[Event] {e.User.Name} has been unbanned from the server!");
var channel = e.Server.FindChannels("general", ChannelType.Text).FirstOrDefault();
await channel.SendMessage($"{e.User.Name} has been unbanned from the server! :D");
};
// installing the command scripts
commands = client.GetService<CommandService>(true);
// AdminCommands a_commands = new AdminCommands(client,conscr,commands);
BasicCommands b_commands = new BasicCommands(client,conscr,commands,newTarget1);
Games g_Commands = new Games(client,conscr,commands);
MusicController m_Commands = new MusicController(client,conscr,commands,true);
client.ChannelCreated += async (s,e) => {
conscr.Print("Special", $"[Event] {e.Channel.Name} has been created in server {e.Channel.Server.Name}!");
Console.Beep();
};
client.ChannelDestroyed += async (s, e) => {
conscr.Print("Error", $"[Event] {e.Channel.Name} has been destroyed in server {e.Channel.Server.Name}!");
};
client.ChannelUpdated += async (s, e) => {
conscr.Print("Special", $"[Event] Channel updated: {e}.");
Console.Beep();
};
client.JoinedServer += async (s,e) => {
conscr.Print("Special", $"[Event] Joined Server: {e.Server.Name}.");
conscr.Print("Special", $"Owner: {e.Server.Owner.Name} (nickname: {e.Server.Owner.Nickname}).");
var defaultChan = e.Server.FindChannels("general", ChannelType.Text).FirstOrDefault();
if (defaultChan != null){
await defaultChan.SendMessage($"Hello there people of {e.Server.Name}! My name is SucyBot and I am glad to be your assistant. <3\nIf you would like more information about me, please type in >help in the chat below.");
}
};
// printing out the final stuff for the console
conscr.Print("Normal", "----------------------------------------------------------");
conscr.Print("Normal", " ");
conscr.Print("Normal", "Console Output:");
Console.Beep();
// executing the client
client.ExecuteAndWait(async() => {
await client.Connect(newTarget1.Token, TokenType.Bot);
client.SetGame("Use >help.");
client.SetStatus(UserStatus.Online);
});
} catch (Exception e) {
conscr.Print("Error", $"[Error] {e.Message}");
Console.Beep();
conscr.Wait(3);
Environment.Exit(0);
}
}
// private functions
private void Log (object sender, LogMessageEventArgs e) {
conscr.Print("Cyan",$"{e.Message}");
}
private void configReader() {
try {
if (newTarget1.Configured == false || string.IsNullOrWhiteSpace(newTarget1.Token) || newTarget1.OwnerId == 0) {
conscr.Print("Warning","Bot information has not been properly configured. Setting up initialization...");
conscr.Wait(3);
initializeChecker();
} else {
conscr.Print("Normal", "Configuration file has been successfully initialized.");
}
} catch (Exception e) {
conscr.Print("Error", "Error: Cannot find configuration file..");
conscr.Wait(3);
Environment.Exit(0);
}
}
private void checkAPIKeys() {
try {
conscr.Print("Normal","Checking for Google API key...");
conscr.Wait(2);
if (string.IsNullOrWhiteSpace(newTarget1.GoogleAPIKey)) {
conscr.Print("Warning", "No Google API key found within the configuration file. Music from Youtube is disabled.");
} else {
conscr.Print("Hacker", "Google API key has been obtained. Music from Youtube is now enabled.");
conscr.Print("Hacker", $"Key ID: {newTarget1.GoogleAPIKey}");
}
conscr.Wait(2);
conscr.Print("Normal", "Checking for SoundCloud Client ID...");
conscr.Wait(2);
if (string.IsNullOrWhiteSpace(newTarget1.SoundCloudClientID)) {
conscr.Print("Warning", "No Soundcloud Client ID found within the configuration file. Soundcloud streaming is disabled.");
} else {
conscr.Print("Hacker", "Soundcloud Client ID has been obtained. Soundcloud streaming enabled.");
conscr.Print("Hacker", $"Client ID: {newTarget1.SoundCloudClientID}");
}
conscr.Wait(2);
} catch (Exception e) {
conscr.Print("Error", "Error: Cannot find configuration file..");
Console.Beep();
conscr.Wait(3);
Environment.Exit(0);
}
}
private void initializeChecker() {
if (newTarget1.Token == null) {
Console.Beep();
conscr.Print("Special", "Please Enter Token: ");
newTarget1.Token = Console.ReadLine();
}
if (newTarget1.OwnerId == 0) {
Console.Beep();
conscr.Print("Special", "Please Enter your client id (make sure you set discord to Developer Mode and right click on your own username in a chatroom!): ");
string lol = Convert.ToString(Console.ReadLine());
newTarget1.OwnerId = Convert.ToUInt64(lol);
}
Console.Beep();
conscr.Print("Special", "Setting up configuration (please wait)...");
conscr.Wait(3);
Console.Beep();
conscr.Print("Hacker", "Configuration completed!");
conscr.Print("Special", $"Token: {newTarget1.Token}");
conscr.Print("Special", $"ClientId: {newTarget1.OwnerId}");
newTarget1.Configured = true;
bcfgChanged = true;
conscr.Wait(3);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System
{
internal static partial class SR
{
// This method is used to decide if we need to append the exception message parameters to the message when calling SR.Format.
// by default it returns false.
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool UsingResourceKeys()
{
return false;
}
// Needed for debugger integration
internal static string? GetResourceString(string resourceKey)
{
return GetResourceString(resourceKey, string.Empty);
}
internal static string GetResourceString(string resourceKey, string? defaultString)
{
string? resourceString = null;
try { resourceString = InternalGetResourceString(resourceKey); }
catch (MissingManifestResourceException) { }
if (defaultString != null && resourceKey.Equals(resourceString, StringComparison.Ordinal))
{
return defaultString;
}
return resourceString!; // only null if missing resource
}
private static readonly object _lock = new object();
private static List<string>? _currentlyLoading;
private static int _infinitelyRecursingCount;
private static bool _resourceManagerInited = false;
private static string? InternalGetResourceString(string? key)
{
if (string.IsNullOrEmpty(key))
{
Debug.Fail("SR::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?");
return key!;
}
// We have a somewhat common potential for infinite
// loops with mscorlib's ResourceManager. If "potentially dangerous"
// code throws an exception, we will get into an infinite loop
// inside the ResourceManager and this "potentially dangerous" code.
// Potentially dangerous code includes the IO package, CultureInfo,
// parts of the loader, some parts of Reflection, Security (including
// custom user-written permissions that may parse an XML file at
// class load time), assembly load event handlers, etc. Essentially,
// this is not a bounded set of code, and we need to fix the problem.
// Fortunately, this is limited to mscorlib's error lookups and is NOT
// a general problem for all user code using the ResourceManager.
// The solution is to make sure only one thread at a time can call
// GetResourceString. Also, since resource lookups can be
// reentrant, if the same thread comes into GetResourceString
// twice looking for the exact same resource name before
// returning, we're going into an infinite loop and we should
// return a bogus string.
bool lockTaken = false;
try
{
Monitor.Enter(_lock, ref lockTaken);
// Are we recursively looking up the same resource? Note - our backout code will set
// the ResourceHelper's currentlyLoading stack to null if an exception occurs.
if (_currentlyLoading != null && _currentlyLoading.Count > 0 && _currentlyLoading.LastIndexOf(key) != -1)
{
// We can start infinitely recursing for one resource lookup,
// then during our failure reporting, start infinitely recursing again.
// avoid that.
if (_infinitelyRecursingCount > 0)
{
return key;
}
_infinitelyRecursingCount++;
// Note: our infrastructure for reporting this exception will again cause resource lookup.
// This is the most direct way of dealing with that problem.
string message = $"Infinite recursion during resource lookup within {System.CoreLib.Name}. This may be a bug in {System.CoreLib.Name}, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names. Resource name: {key}";
Environment.FailFast(message);
}
_currentlyLoading ??= new List<string>();
// Call class constructors preemptively, so that we cannot get into an infinite
// loop constructing a TypeInitializationException. If this were omitted,
// we could get the Infinite recursion assert above by failing type initialization
// between the Push and Pop calls below.
if (!_resourceManagerInited)
{
RuntimeHelpers.RunClassConstructor(typeof(ResourceManager).TypeHandle);
RuntimeHelpers.RunClassConstructor(typeof(ResourceReader).TypeHandle);
RuntimeHelpers.RunClassConstructor(typeof(RuntimeResourceSet).TypeHandle);
RuntimeHelpers.RunClassConstructor(typeof(BinaryReader).TypeHandle);
_resourceManagerInited = true;
}
_currentlyLoading.Add(key); // Push
string? s = ResourceManager.GetString(key, null);
_currentlyLoading.RemoveAt(_currentlyLoading.Count - 1); // Pop
Debug.Assert(s != null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called SR.GetResourceString. Resource name was: \"" + key + "\"");
return s ?? key;
}
catch
{
if (lockTaken)
{
// Backout code - throw away potentially corrupt state
s_resourceManager = null;
_currentlyLoading = null;
}
throw;
}
finally
{
if (lockTaken)
{
Monitor.Exit(_lock);
}
}
}
internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
{
if (args != null)
{
if (UsingResourceKeys())
{
return resourceFormat + ", " + string.Join(", ", args);
}
return string.Format(provider, resourceFormat, args);
}
return resourceFormat;
}
internal static string Format(string resourceFormat, params object?[]? args)
{
if (args != null)
{
if (UsingResourceKeys())
{
return resourceFormat + ", " + string.Join(", ", args);
}
return string.Format(resourceFormat, args);
}
return resourceFormat;
}
internal static string Format(string resourceFormat, object? p1)
{
if (UsingResourceKeys())
{
return string.Join(", ", resourceFormat, p1);
}
return string.Format(resourceFormat, p1);
}
internal static string Format(string resourceFormat, object? p1, object? p2)
{
if (UsingResourceKeys())
{
return string.Join(", ", resourceFormat, p1, p2);
}
return string.Format(resourceFormat, p1, p2);
}
internal static string Format(string resourceFormat, object? p1, object? p2, object? p3)
{
if (UsingResourceKeys())
{
return string.Join(", ", resourceFormat, p1, p2, p3);
}
return string.Format(resourceFormat, p1, p2, p3);
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/ClassDef/*'/>
[ToolboxItem(false)]
internal class VS2003AutoHideStrip : AutoHideStripBase
{
private class TabVS2003 : Tab
{
internal TabVS2003(IDockContent content)
: base(content)
{
}
private int m_tabX = 0;
protected internal int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth = 0;
protected internal int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
}
private const int _ImageHeight = 16;
private const int _ImageWidth = 16;
private const int _ImageGapTop = 2;
private const int _ImageGapLeft = 4;
private const int _ImageGapRight = 4;
private const int _ImageGapBottom = 2;
private const int _TextGapLeft = 4;
private const int _TextGapRight = 10;
private const int _TabGapTop = 3;
private const int _TabGapLeft = 2;
private const int _TabGapBetween = 10;
private static Matrix _matrixIdentity;
private static DockState[] _dockStates;
#region Customizable Properties
private static StringFormat _stringFormatTabHorizontal = null;
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="StringFormatTabHorizontal"]/*'/>
protected virtual StringFormat StringFormatTabHorizontal
{
get
{
if (_stringFormatTabHorizontal == null)
{
_stringFormatTabHorizontal = new StringFormat();
_stringFormatTabHorizontal.Alignment = StringAlignment.Near;
_stringFormatTabHorizontal.LineAlignment = StringAlignment.Center;
_stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap;
}
return _stringFormatTabHorizontal;
}
}
private static StringFormat _stringFormatTabVertical;
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="StringFormatTabVertical"]/*'/>
protected virtual StringFormat StringFormatTabVertical
{
get
{
if (_stringFormatTabVertical == null)
{
_stringFormatTabVertical = new StringFormat();
_stringFormatTabVertical.Alignment = StringAlignment.Near;
_stringFormatTabVertical.LineAlignment = StringAlignment.Center;
_stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
}
return _stringFormatTabVertical;
}
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageHeight"]/*'/>
protected virtual int ImageHeight
{
get { return _ImageHeight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageWidth"]/*'/>
protected virtual int ImageWidth
{
get { return _ImageWidth; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapTop"]/*'/>
protected virtual int ImageGapTop
{
get { return _ImageGapTop; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapLeft"]/*'/>
protected virtual int ImageGapLeft
{
get { return _ImageGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapRight"]/*'/>
protected virtual int ImageGapRight
{
get { return _ImageGapRight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapBottom"]/*'/>
protected virtual int ImageGapBottom
{
get { return _ImageGapBottom; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TextGapLeft"]/*'/>
protected virtual int TextGapLeft
{
get { return _TextGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TextGapRight"]/*'/>
protected virtual int TextGapRight
{
get { return _TextGapRight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapTop"]/*'/>
protected virtual int TabGapTop
{
get { return _TabGapTop; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapLeft"]/*'/>
protected virtual int TabGapLeft
{
get { return _TabGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapBetween"]/*'/>
protected virtual int TabGapBetween
{
get { return _TabGapBetween; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="BrushTabBackground"]/*'/>
protected virtual Brush BrushTabBackground
{
get { return SystemBrushes.Control; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="PenTabBorder"]/*'/>
protected virtual Pen PenTabBorder
{
get { return SystemPens.GrayText; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="BrushTabText"]/*'/>
protected virtual Brush BrushTabText
{
get { return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark); }
}
#endregion
private Matrix MatrixIdentity
{
get { return _matrixIdentity; }
}
private DockState[] DockStates
{
get { return _dockStates; }
}
static VS2003AutoHideStrip()
{
_matrixIdentity = new Matrix();
_dockStates = new DockState[4];
_dockStates[0] = DockState.DockLeftAutoHide;
_dockStates[1] = DockState.DockRightAutoHide;
_dockStates[2] = DockState.DockTopAutoHide;
_dockStates[3] = DockState.DockBottomAutoHide;
}
public VS2003AutoHideStrip(DockPanel panel) : base(panel)
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
BackColor = Color.WhiteSmoke;
}
/// <exclude/>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
DrawTabStrip(g);
}
/// <exclude/>
protected override void OnLayout(LayoutEventArgs levent)
{
CalculateTabs();
base.OnLayout (levent);
}
private void DrawTabStrip(Graphics g)
{
DrawTabStrip(g, DockState.DockTopAutoHide);
DrawTabStrip(g, DockState.DockBottomAutoHide);
DrawTabStrip(g, DockState.DockLeftAutoHide);
DrawTabStrip(g, DockState.DockRightAutoHide);
}
private void DrawTabStrip(Graphics g, DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return;
Matrix matrixIdentity = g.Transform;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
Matrix matrixRotated = new Matrix();
matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
g.Transform = matrixRotated;
}
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2003 tab in pane.AutoHideTabs)
DrawTab(g, tab);
}
g.Transform = matrixIdentity;
}
private void CalculateTabs()
{
CalculateTabs(DockState.DockTopAutoHide);
CalculateTabs(DockState.DockBottomAutoHide);
CalculateTabs(DockState.DockLeftAutoHide);
CalculateTabs(DockState.DockRightAutoHide);
}
private void CalculateTabs(DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight/ImageHeight);
using (Graphics g = CreateGraphics())
{
int x = TabGapLeft + rectTabStrip.X;
foreach (Pane pane in GetPanes(dockState))
{
int maxWidth = 0;
foreach (TabVS2003 tab in pane.AutoHideTabs)
{
int width = imageWidth + ImageGapLeft + ImageGapRight +
(int)g.MeasureString(tab.Content.DockHandler.TabText, Font).Width + 1 +
TextGapLeft + TextGapRight;
if (width > maxWidth)
maxWidth = width;
}
foreach (TabVS2003 tab in pane.AutoHideTabs)
{
tab.TabX = x;
if (tab.Content == pane.DockPane.ActiveContent)
tab.TabWidth = maxWidth;
else
tab.TabWidth = imageWidth + ImageGapLeft + ImageGapRight;
x += tab.TabWidth;
}
x += TabGapBetween;
}
}
}
private void DrawTab(Graphics g, TabVS2003 tab)
{
Rectangle rectTab = GetTabRectangle(tab);
if (rectTab.IsEmpty)
return;
DockState dockState = tab.Content.DockHandler.DockState;
IDockContent content = tab.Content;
OnBeginDrawTab(tab);
Brush brushTabBackGround = BrushTabBackground;
Pen penTabBorder = PenTabBorder;
Brush brushTabText = BrushTabText;
g.FillRectangle(brushTabBackGround, rectTab);
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Left, rectTab.Bottom);
g.DrawLine(penTabBorder, rectTab.Right, rectTab.Top, rectTab.Right, rectTab.Bottom);
if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
else
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Right, rectTab.Top);
// Set no rotate for drawing icon and text
Matrix matrixRotate = g.Transform;
g.Transform = MatrixIdentity;
// Draw the icon
Rectangle rectImage = rectTab;
rectImage.X += ImageGapLeft;
rectImage.Y += ImageGapTop;
int imageHeight = rectTab.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight/ImageHeight);
rectImage.Height = imageHeight;
rectImage.Width = imageWidth;
rectImage = GetTransformedRectangle(dockState, rectImage);
g.DrawIcon(((Form)content).Icon, rectImage);
// Draw the text
if (content == content.DockHandler.Pane.ActiveContent)
{
Rectangle rectText = rectTab;
rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText = GetTransformedRectangle(dockState, rectText);
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabVertical);
else
g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabHorizontal);
}
// Set rotate back
g.Transform = matrixRotate;
OnEndDrawTab(tab);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState)
{
return GetLogicalTabStripRectangle(dockState, false);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed)
{
if (!DockHelper.IsDockStateAutoHide(dockState))
return Rectangle.Empty;
int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count;
int rightPanes = GetPanes(DockState.DockRightAutoHide).Count;
int topPanes = GetPanes(DockState.DockTopAutoHide).Count;
int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count;
int x, y, width, height;
height = MeasureHeight();
if (dockState == DockState.DockLeftAutoHide && leftPanes > 0)
{
x = 0;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height);
}
else if (dockState == DockState.DockRightAutoHide && rightPanes > 0)
{
x = Width - height;
if (leftPanes != 0 && x < height)
x = height;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height);
}
else if (dockState == DockState.DockTopAutoHide && topPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = 0;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = Height - height;
if (topPanes != 0 && y < height)
y = height;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else
return Rectangle.Empty;
if (width == 0 || height == 0)
{
return Rectangle.Empty;
}
var rect = new Rectangle(x, y, width, height);
return transformed ? GetTransformedRectangle(dockState, rect) : rect;
}
private Rectangle GetTabRectangle(TabVS2003 tab)
{
return GetTabRectangle(tab, false);
}
private Rectangle GetTabRectangle(TabVS2003 tab, bool transformed)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return Rectangle.Empty;
int x = tab.TabX;
int y = rectTabStrip.Y +
(dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ?
0 : TabGapTop);
int width = tab.TabWidth;
int height = rectTabStrip.Height - TabGapTop;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect)
{
if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide)
return rect;
PointF[] pts = new PointF[1];
// the center of the rectangle
pts[0].X = (float)rect.X + (float)rect.Width / 2;
pts[0].Y = (float)rect.Y + (float)rect.Height / 2;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
using (Matrix matrix = new Matrix())
{
matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
matrix.TransformPoints(pts);
}
return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F),
(int)(pts[0].Y - (float)rect.Width / 2 + .5F),
rect.Height, rect.Width);
}
/// <exclude />
protected override IDockContent HitTest(Point point)
{
foreach(DockState state in DockStates)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true);
if (!rectTabStrip.Contains(point))
continue;
foreach(Pane pane in GetPanes(state))
{
foreach(TabVS2003 tab in pane.AutoHideTabs)
{
Rectangle rectTab = GetTabRectangle(tab, true);
rectTab.Intersect(rectTabStrip);
if (rectTab.Contains(point))
return tab.Content;
}
}
}
return null;
}
protected override Rectangle GetTabBounds(Tab tab)
{
return GetTabRectangle((TabVS2003)tab, true);
}
/// <exclude/>
protected override int MeasureHeight()
{
return Math.Max(ImageGapBottom +
ImageGapTop + ImageHeight,
Font.Height) + TabGapTop;
}
/// <exclude/>
protected override void OnRefreshChanges()
{
CalculateTabs();
Invalidate();
}
protected override AutoHideStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2003(content);
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Method[@name="OnBeginDrawTab(AutoHideTab)"]/*'/>
protected virtual void OnBeginDrawTab(Tab tab)
{
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Method[@name="OnEndDrawTab(AutoHideTab)"]/*'/>
protected virtual void OnEndDrawTab(Tab tab)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace SpriteToParticlesAsset
{
#if UNITY_5_3_OR_NEWER
/// <summary>
/// This class is a modification on the class shared publicly by Glenn Powell (glennpow) tha can be found here
/// http://forum.unity3d.com/threads/free-script-particle-systems-in-ui-screen-space-overlay.406862/
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(CanvasRenderer))]
[RequireComponent(typeof(ParticleSystem))]
[AddComponentMenu("UI/Effects/Extensions/UI Particle System")]
public class UIParticleRenderer : MaskableGraphic
{
[Tooltip("Having this enabled run the system in LateUpdate rather than in Update making it faster but less precise (more clunky)")]
public bool fixedTime = true;
private Transform _transform;
private ParticleSystem pSystem;
private ParticleSystem.Particle[] particles;
private UIVertex[] _quad = new UIVertex[4];
private Vector4 imageUV = Vector4.zero;
private ParticleSystem.TextureSheetAnimationModule textureSheetAnimation;
private int textureSheetAnimationFrames;
private Vector2 textureSheetAnimationFrameSize;
private ParticleSystemRenderer pRenderer;
private Material currentMaterial;
private Texture currentTexture;
#if UNITY_5_5_OR_NEWER
private ParticleSystem.MainModule mainModule;
#endif
public override Texture mainTexture
{
get
{
return currentTexture;
}
}
protected bool Initialize()
{
// initialize members
if (_transform == null)
{
_transform = transform;
}
if (pSystem == null)
{
pSystem = GetComponent<ParticleSystem>();
if (pSystem == null)
{
return false;
}
#if UNITY_5_5_OR_NEWER
mainModule = pSystem.main;
if (pSystem.main.maxParticles > 14000)
{
mainModule.maxParticles = 14000;
}
#else
if (pSystem.maxParticles > 14000)
pSystem.maxParticles = 14000;
#endif
pRenderer = pSystem.GetComponent<ParticleSystemRenderer>();
if (pRenderer != null)
pRenderer.enabled = false;
if (material == null)
{
Shader foundShader = Shader.Find("UI/Particles/Additive");
Material pMaterial = new Material(foundShader);
material = pMaterial;
}
currentMaterial = material;
if (currentMaterial && currentMaterial.HasProperty("_MainTex"))
{
currentTexture = currentMaterial.mainTexture;
if (currentTexture == null)
currentTexture = Texture2D.whiteTexture;
}
material = currentMaterial;
// automatically set scaling
#if UNITY_5_5_OR_NEWER
mainModule.scalingMode = ParticleSystemScalingMode.Hierarchy;
#else
pSystem.scalingMode = ParticleSystemScalingMode.Hierarchy;
#endif
particles = null;
}
#if UNITY_5_5_OR_NEWER
if (particles == null)
particles = new ParticleSystem.Particle[pSystem.main.maxParticles];
#else
if (particles == null)
particles = new ParticleSystem.Particle[pSystem.maxParticles];
#endif
imageUV = new Vector4(0, 0, 1, 1);
// prepare texture sheet animation
textureSheetAnimation = pSystem.textureSheetAnimation;
textureSheetAnimationFrames = 0;
textureSheetAnimationFrameSize = Vector2.zero;
if (textureSheetAnimation.enabled)
{
textureSheetAnimationFrames = textureSheetAnimation.numTilesX * textureSheetAnimation.numTilesY;
textureSheetAnimationFrameSize = new Vector2(1f / textureSheetAnimation.numTilesX, 1f / textureSheetAnimation.numTilesY);
}
return true;
}
protected override void Awake()
{
base.Awake();
if (!Initialize())
enabled = false;
}
protected override void OnPopulateMesh(VertexHelper vh)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
if (!Initialize())
{
return;
}
}
#endif
// prepare vertices
vh.Clear();
if (!gameObject.activeInHierarchy)
{
return;
}
Vector2 temp = Vector2.zero;
Vector2 corner1 = Vector2.zero;
Vector2 corner2 = Vector2.zero;
// iterate through current particles
int count = pSystem.GetParticles(particles);
for (int i = 0; i < count; ++i)
{
ParticleSystem.Particle particle = particles[i];
// get particle properties
#if UNITY_5_5_OR_NEWER
Vector2 position = (mainModule.simulationSpace == ParticleSystemSimulationSpace.Local ? particle.position : _transform.InverseTransformPoint(particle.position));
#else
Vector2 position = (pSystem.simulationSpace == ParticleSystemSimulationSpace.Local ? particle.position : _transform.InverseTransformPoint(particle.position));
#endif
float rotation = -particle.rotation * Mathf.Deg2Rad;
float rotation90 = rotation + Mathf.PI / 2;
Color32 color = particle.GetCurrentColor(pSystem);
float size = particle.GetCurrentSize(pSystem) * 0.5f;
// apply scale
#if UNITY_5_5_OR_NEWER
if (mainModule.scalingMode == ParticleSystemScalingMode.Shape)
position /= canvas.scaleFactor;
#else
if (pSystem.scalingMode == ParticleSystemScalingMode.Shape)
position /= canvas.scaleFactor;
#endif
// apply texture sheet animation
Vector4 particleUV = imageUV;
if (textureSheetAnimation.enabled)
{
#if UNITY_5_5_OR_NEWER
float frameProgress = textureSheetAnimation.frameOverTime.curveMin.Evaluate(1 - (particle.remainingLifetime / particle.startLifetime));
#else
float frameProgress = 1 - (particle.lifetime / particle.startLifetime);
#endif
frameProgress = Mathf.Repeat(frameProgress * textureSheetAnimation.cycleCount, 1);
int frame = 0;
switch (textureSheetAnimation.animation)
{
case ParticleSystemAnimationType.WholeSheet:
frame = Mathf.FloorToInt(frameProgress * textureSheetAnimationFrames);
break;
case ParticleSystemAnimationType.SingleRow:
frame = Mathf.FloorToInt(frameProgress * textureSheetAnimation.numTilesX);
int row = textureSheetAnimation.rowIndex;
// if (textureSheetAnimation.useRandomRow) { // FIXME - is this handled internally by rowIndex?
// row = Random.Range(0, textureSheetAnimation.numTilesY, using: particle.randomSeed);
// }
frame += row * textureSheetAnimation.numTilesX;
break;
}
frame %= textureSheetAnimationFrames;
particleUV.x = (frame % textureSheetAnimation.numTilesX) * textureSheetAnimationFrameSize.x;
particleUV.y = Mathf.FloorToInt(frame / textureSheetAnimation.numTilesX) * textureSheetAnimationFrameSize.y;
particleUV.z = particleUV.x + textureSheetAnimationFrameSize.x;
particleUV.w = particleUV.y + textureSheetAnimationFrameSize.y;
}
temp.x = particleUV.x;
temp.y = particleUV.y;
_quad[0] = UIVertex.simpleVert;
_quad[0].color = color;
_quad[0].uv0 = temp;
temp.x = particleUV.x;
temp.y = particleUV.w;
_quad[1] = UIVertex.simpleVert;
_quad[1].color = color;
_quad[1].uv0 = temp;
temp.x = particleUV.z;
temp.y = particleUV.w;
_quad[2] = UIVertex.simpleVert;
_quad[2].color = color;
_quad[2].uv0 = temp;
temp.x = particleUV.z;
temp.y = particleUV.y;
_quad[3] = UIVertex.simpleVert;
_quad[3].color = color;
_quad[3].uv0 = temp;
if (rotation == 0)
{
// no rotation
corner1.x = position.x - size;
corner1.y = position.y - size;
corner2.x = position.x + size;
corner2.y = position.y + size;
temp.x = corner1.x;
temp.y = corner1.y;
_quad[0].position = temp;
temp.x = corner1.x;
temp.y = corner2.y;
_quad[1].position = temp;
temp.x = corner2.x;
temp.y = corner2.y;
_quad[2].position = temp;
temp.x = corner2.x;
temp.y = corner1.y;
_quad[3].position = temp;
}
else
{
// apply rotation
Vector2 right = new Vector2(Mathf.Cos(rotation), Mathf.Sin(rotation)) * size;
Vector2 up = new Vector2(Mathf.Cos(rotation90), Mathf.Sin(rotation90)) * size;
_quad[0].position = position - right - up;
_quad[1].position = position - right + up;
_quad[2].position = position + right + up;
_quad[3].position = position + right - up;
}
vh.AddUIVertexQuad(_quad);
}
}
void Update()
{
if (!fixedTime && Application.isPlaying)
{
pSystem.Simulate(Time.unscaledDeltaTime, false, false, true);
SetAllDirty();
if ((currentMaterial!= null && currentTexture != currentMaterial.mainTexture) ||
(material!=null && currentMaterial != null && material.shader != currentMaterial.shader))
{
pSystem = null;
Initialize();
}
}
}
void LateUpdate()
{
if (!Application.isPlaying)
{
SetAllDirty();
}
else
{
if (fixedTime)
{
pSystem.Simulate(Time.unscaledDeltaTime, false, false, true);
SetAllDirty();
if ((currentMaterial != null && currentTexture != currentMaterial.mainTexture) ||
(material != null && currentMaterial != null && material.shader != currentMaterial.shader))
{
pSystem = null;
Initialize();
}
}
}
if (material == currentMaterial)
return;
pSystem = null;
Initialize();
}
}
#endif
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using NUnit.Framework;
using System.Linq;
using Cassandra.IntegrationTests.SimulacronAPI.Models.Logs;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement.Simulacron;
using Cassandra.Tests;
namespace Cassandra.IntegrationTests.Core
{
[TestFixture, Category(TestCategory.Short)]
public class ConsistencyTests : TestGlobals
{
private const string Query = "SELECT id, value from verifyconsistency";
/// Tests that the default consistency level for queries is LOCAL_ONE
///
/// LocalOne_Is_Default_Consistency tests that the default consistency level for all queries is LOCAL_ONE. It performs
/// a simple select statement and verifies that the result set metadata shows that the achieved consistency level is LOCAL_ONE.
///
/// @since 3.0.0
/// @jira_ticket CSHARP-378
/// @expected_result The default consistency level should be LOCAL_ONE
///
/// @test_category consistency
[Test]
public void Should_UseCLLocalOne_When_NotSpecifiedXDefaultX()
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3" } ))
using (var cluster = ClusterBuilder()
.AddContactPoint(simulacronCluster.InitialContactPoint).Build())
{
var session = cluster.Connect();
var rs = session.Execute(new SimpleStatement(Query));
Assert.AreEqual(ConsistencyLevel.LocalOne, rs.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, Query, ConsistencyLevel.LocalOne);
}
}
[Test]
[TestCase(ConsistencyLevel.Quorum)]
[TestCase(ConsistencyLevel.All)]
[TestCase(ConsistencyLevel.Any)]
[TestCase(ConsistencyLevel.One)]
[TestCase(ConsistencyLevel.Two)]
[TestCase(ConsistencyLevel.Three)]
[TestCase(ConsistencyLevel.LocalOne)]
[TestCase(ConsistencyLevel.LocalQuorum)]
public void Should_UseQueryOptionsCL_When_NotSetAtSimpleStatement(ConsistencyLevel consistencyLevel)
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } ))
using (var cluster = ClusterBuilder()
.WithQueryOptions(new QueryOptions().SetConsistencyLevel(consistencyLevel))
.AddContactPoint(simulacronCluster.InitialContactPoint).Build())
{
var session = cluster.Connect();
var simpleStatement = new SimpleStatement(Query);
var result = session.Execute(simpleStatement);
Assert.AreEqual(consistencyLevel, result.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, Query, consistencyLevel);
}
}
[Test]
[TestCase(ConsistencyLevel.Serial)]
[TestCase(ConsistencyLevel.LocalSerial)]
public void Should_UseQueryOptionsSerialCL_When_NotSetAtSimpleStatement(ConsistencyLevel serialConsistency)
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } ))
using (var cluster = ClusterBuilder()
.WithQueryOptions(new QueryOptions().SetSerialConsistencyLevel(serialConsistency))
.AddContactPoint(simulacronCluster.InitialContactPoint).Build())
{
const string conditionalQuery = "insert into tbl_serial (id, value) values (1, 2) if not exists";
var session = cluster.Connect();
var simpleStatement = new SimpleStatement(conditionalQuery);
var result = session.Execute(simpleStatement);
Assert.AreEqual(ConsistencyLevel.LocalOne, result.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, conditionalQuery, ConsistencyLevel.LocalOne, serialConsistency);
}
}
[Test]
[TestCase(ConsistencyLevel.Quorum)]
[TestCase(ConsistencyLevel.All)]
[TestCase(ConsistencyLevel.Any)]
[TestCase(ConsistencyLevel.One)]
[TestCase(ConsistencyLevel.Two)]
[TestCase(ConsistencyLevel.Three)]
[TestCase(ConsistencyLevel.LocalOne)]
[TestCase(ConsistencyLevel.LocalQuorum)]
public void Should_UseSimpleStatementCL_When_Set(ConsistencyLevel consistencyLevel)
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } ))
using (var cluster = ClusterBuilder()
.WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.Any))
.AddContactPoint(simulacronCluster.InitialContactPoint).Build())
{
var session = cluster.Connect();
var simpleStatement = new SimpleStatement(Query).SetConsistencyLevel(consistencyLevel);
var result = session.Execute(simpleStatement);
Assert.AreEqual(consistencyLevel, result.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, Query, consistencyLevel);
}
}
[Test]
[TestCase(ConsistencyLevel.Quorum, ConsistencyLevel.Serial)]
[TestCase(ConsistencyLevel.Quorum, ConsistencyLevel.LocalSerial)]
public void Should_UseSerialConsistencyLevelSpecified_When_ConditionalQuery(
ConsistencyLevel consistencyLevel, ConsistencyLevel serialConsistency)
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } ))
using (var cluster = ClusterBuilder()
.AddContactPoint(simulacronCluster.InitialContactPoint).Build())
{
const string conditionalQuery = "update tbl_serial set value=2 where id=1 if exists";
var session = cluster.Connect();
var simpleStatement = new SimpleStatement(conditionalQuery)
.SetConsistencyLevel(consistencyLevel)
.SetSerialConsistencyLevel(serialConsistency);
var result = session.Execute(simpleStatement);
Assert.AreEqual(consistencyLevel, result.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, conditionalQuery, consistencyLevel, serialConsistency);
}
}
[Test]
[TestCase(ConsistencyLevel.Quorum, ConsistencyLevel.Serial)]
[TestCase(ConsistencyLevel.LocalQuorum, ConsistencyLevel.LocalSerial)]
public void Should_UseSerialConsistencyLevel_From_QueryOptions(
ConsistencyLevel consistencyLevel, ConsistencyLevel serialConsistency)
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } ))
using (var cluster = ClusterBuilder()
.AddContactPoint(simulacronCluster.InitialContactPoint)
.WithQueryOptions(new QueryOptions()
.SetConsistencyLevel(consistencyLevel)
.SetSerialConsistencyLevel(serialConsistency))
.Build())
{
const string conditionalQuery = "update tbl_serial set value=3 where id=2 if exists";
var session = cluster.Connect();
var simpleStatement = new SimpleStatement(conditionalQuery);
var result = session.Execute(simpleStatement);
Assert.AreEqual(consistencyLevel, result.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, conditionalQuery, consistencyLevel, serialConsistency);
}
}
[Test]
[TestCase(ConsistencyLevel.Quorum)]
[TestCase(ConsistencyLevel.All)]
[TestCase(ConsistencyLevel.Any)]
[TestCase(ConsistencyLevel.One)]
[TestCase(ConsistencyLevel.Two)]
[TestCase(ConsistencyLevel.Three)]
[TestCase(ConsistencyLevel.LocalOne)]
[TestCase(ConsistencyLevel.LocalQuorum)]
public void Should_UseQueryOptionsCL_When_NotSetAtPreparedStatement(ConsistencyLevel consistencyLevel)
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } ))
using (var cluster = ClusterBuilder()
.WithQueryOptions(new QueryOptions().SetConsistencyLevel(consistencyLevel))
.AddContactPoint(simulacronCluster.InitialContactPoint).Build())
{
var session = cluster.Connect();
const string prepQuery = "select id, value from tbl_consistency where id=?";
var prepStmt = session.Prepare(prepQuery);
var boundStmt = prepStmt.Bind(1);
var result = session.Execute(boundStmt);
Assert.AreEqual(consistencyLevel, result.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, prepQuery, consistencyLevel, null, QueryType.Execute);
}
}
[Test]
[TestCase(ConsistencyLevel.Serial)]
[TestCase(ConsistencyLevel.LocalSerial)]
public void Should_UseQueryOptionsSerialCL_When_NotSetAtPreparedStatement(ConsistencyLevel consistencyLevel)
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } ))
using (var cluster = ClusterBuilder()
.WithQueryOptions(new QueryOptions().SetSerialConsistencyLevel(consistencyLevel))
.AddContactPoint(simulacronCluster.InitialContactPoint).Build())
{
var session = cluster.Connect();
const string prepQuery = "select id, value from tbl_consistency where id=? if exists";
var prepStmt = session.Prepare(prepQuery);
var boundStmt = prepStmt.Bind(1);
var result = session.Execute(boundStmt);
Assert.AreEqual(ConsistencyLevel.LocalOne, result.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, prepQuery, ConsistencyLevel.LocalOne, consistencyLevel, QueryType.Execute);
}
}
[Test]
[TestCase(ConsistencyLevel.Quorum)]
[TestCase(ConsistencyLevel.All)]
[TestCase(ConsistencyLevel.Any)]
[TestCase(ConsistencyLevel.One)]
[TestCase(ConsistencyLevel.Two)]
[TestCase(ConsistencyLevel.Three)]
[TestCase(ConsistencyLevel.LocalOne)]
[TestCase(ConsistencyLevel.LocalQuorum)]
public void Should_UsePreparedStatementCL_When_Set(ConsistencyLevel consistencyLevel)
{
using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions { Nodes = "3,3" } ))
using (var cluster = ClusterBuilder()
.AddContactPoint(simulacronCluster.InitialContactPoint).Build())
{
var session = cluster.Connect();
const string prepQuery = "select id, value from tbl_consistency where id=?";
var prepStmt = session.Prepare(prepQuery);
var boundStmt = prepStmt.Bind(1).SetConsistencyLevel(consistencyLevel);
var result = session.Execute(boundStmt);
Assert.AreEqual(consistencyLevel, result.Info.AchievedConsistency);
VerifyConsistency(simulacronCluster, prepQuery, consistencyLevel, null, QueryType.Execute);
}
}
private static void VerifyConsistency(SimulacronCluster simulacronCluster, string query, ConsistencyLevel consistency,
ConsistencyLevel? serialConsistency = null, QueryType queryType = QueryType.Query)
{
var executedQueries = simulacronCluster.GetQueries(query, queryType);
Assert.NotNull(executedQueries);
var log = executedQueries.First();
Assert.AreEqual(consistency, log.ConsistencyLevel);
if (serialConsistency == null)
{
Assert.AreEqual(ConsistencyLevel.Serial, log.SerialConsistencyLevel);
}
else
{
Assert.AreEqual(serialConsistency, log.SerialConsistencyLevel);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using AutoyaFramework.Settings.Connection;
using UnityEngine.Networking;
/**
implementation of HTTP connection with timeout.
*/
namespace AutoyaFramework.Connections.HTTP
{
public class HTTPConnection
{
// response by string
public IEnumerator Get(string connectionId, Dictionary<string, string> requestHeader, string url, Action<string, int, Dictionary<string, string>, string> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Get(url))
{
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = Encoding.UTF8.GetString(request.downloadHandler.data);
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + result, responseHeaders);
}
}
}
public IEnumerator Post(string connectionId, Dictionary<string, string> requestHeader, string url, string data, Action<string, int, Dictionary<string, string>, string> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Post(url, data))
{
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = Encoding.UTF8.GetString(request.downloadHandler.data);
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + result, responseHeaders);
}
}
}
public IEnumerator Put(string connectionId, Dictionary<string, string> requestHeader, string url, string data, Action<string, int, Dictionary<string, string>, string> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Put(url, data))
{
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = Encoding.UTF8.GetString(request.downloadHandler.data);
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + result, responseHeaders);
}
}
}
public IEnumerator Delete(string connectionId, Dictionary<string, string> requestHeader, string url, Action<string, int, Dictionary<string, string>, string> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Delete(url))
{
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = Encoding.UTF8.GetString(request.downloadHandler.data);
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + result, responseHeaders);
}
}
}
// response by byte[]
public IEnumerator GetByBytes(string connectionId, Dictionary<string, string> requestHeader, string url, Action<string, int, Dictionary<string, string>, byte[]> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Get(url))
{
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = request.downloadHandler.data;
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + result, responseHeaders);
}
}
}
public IEnumerator PostByBytes(string connectionId, Dictionary<string, string> requestHeader, string url, string data, Action<string, int, Dictionary<string, string>, byte[]> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Post(url, data))
{
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = request.downloadHandler.data;
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + Encoding.UTF8.GetString(result), responseHeaders);
}
}
}
public IEnumerator PutByBytes(string connectionId, Dictionary<string, string> requestHeader, string url, string data, Action<string, int, Dictionary<string, string>, byte[]> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Put(url, data))
{
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = request.downloadHandler.data;
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + Encoding.UTF8.GetString(result), responseHeaders);
}
}
}
public IEnumerator DeleteByBytes(string connectionId, Dictionary<string, string> requestHeader, string url, Action<string, int, Dictionary<string, string>, byte[]> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Delete(url))
{
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = request.downloadHandler.data;
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + Encoding.UTF8.GetString(result), responseHeaders);
}
}
}
// request & response by byte[]
public IEnumerator Post(string connectionId, Dictionary<string, string> requestHeader, string url, byte[] data, Action<string, int, Dictionary<string, string>, byte[]> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Post(url, string.Empty))
{
// set data if not 0.
if (0 < data.Length)
{
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(data);
}
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = Encoding.UTF8.GetString(request.downloadHandler.data);
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, request.downloadHandler.data);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + result, responseHeaders);
}
}
}
public IEnumerator Put(string connectionId, Dictionary<string, string> requestHeader, string url, byte[] data, Action<string, int, Dictionary<string, string>, string> succeeded, Action<string, int, string, Dictionary<string, string>> failed, double timeoutSec = 0)
{
var currentDate = DateTime.UtcNow;
var limitTick = (TimeSpan.FromTicks(currentDate.Ticks) + TimeSpan.FromSeconds(timeoutSec)).Ticks;
using (var request = UnityWebRequest.Put(url, data))
{
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(data);
if (requestHeader != null)
{
foreach (var kv in requestHeader)
{
request.SetRequestHeader(kv.Key, kv.Value);
}
}
request.chunkedTransfer = ConnectionSettings.useChunkedTransfer;
var p = request.SendWebRequest();
while (!p.isDone)
{
yield return null;
// check timeout.
if (0 < timeoutSec && limitTick < DateTime.UtcNow.Ticks)
{
request.Abort();
failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, BackyardSettings.HTTP_TIMEOUT_MESSAGE, null);
yield break;
}
}
var responseCode = (int)request.responseCode;
var responseHeaders = request.GetResponseHeaders();
if (request.isNetworkError)
{
failed(connectionId, responseCode, request.error, responseHeaders);
yield break;
}
var result = Encoding.UTF8.GetString(request.downloadHandler.data);
if (200 <= responseCode && responseCode <= 299)
{
succeeded(connectionId, responseCode, responseHeaders, result);
}
else
{
failed(connectionId, responseCode, BackyardSettings.HTTP_CODE_ERROR_SUFFIX + result, responseHeaders);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for GlobalSchedulesOperations.
/// </summary>
public static partial class GlobalSchedulesOperationsExtensions
{
/// <summary>
/// List schedules in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<Schedule> ListBySubscription(this IGlobalSchedulesOperations operations, ODataQuery<Schedule> odataQuery = default(ODataQuery<Schedule>))
{
return Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).ListBySubscriptionAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List schedules in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Schedule>> ListBySubscriptionAsync(this IGlobalSchedulesOperations operations, ODataQuery<Schedule> odataQuery = default(ODataQuery<Schedule>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List schedules in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<Schedule> ListByResourceGroup(this IGlobalSchedulesOperations operations, ODataQuery<Schedule> odataQuery = default(ODataQuery<Schedule>))
{
return Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).ListByResourceGroupAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List schedules in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Schedule>> ListByResourceGroupAsync(this IGlobalSchedulesOperations operations, ODataQuery<Schedule> odataQuery = default(ODataQuery<Schedule>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=status)'
/// </param>
public static Schedule Get(this IGlobalSchedulesOperations operations, string name, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).GetAsync(name, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=status)'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Schedule> GetAsync(this IGlobalSchedulesOperations operations, string name, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(name, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='schedule'>
/// A schedule.
/// </param>
public static Schedule CreateOrUpdate(this IGlobalSchedulesOperations operations, string name, Schedule schedule)
{
return Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).CreateOrUpdateAsync(name, schedule), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='schedule'>
/// A schedule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Schedule> CreateOrUpdateAsync(this IGlobalSchedulesOperations operations, string name, Schedule schedule, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(name, schedule, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
public static void Delete(this IGlobalSchedulesOperations operations, string name)
{
Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).DeleteAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IGlobalSchedulesOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Modify properties of schedules.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='schedule'>
/// A schedule.
/// </param>
public static Schedule Update(this IGlobalSchedulesOperations operations, string name, ScheduleFragment schedule)
{
return Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).UpdateAsync(name, schedule), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Modify properties of schedules.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='schedule'>
/// A schedule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Schedule> UpdateAsync(this IGlobalSchedulesOperations operations, string name, ScheduleFragment schedule, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(name, schedule, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Execute a schedule. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
public static void Execute(this IGlobalSchedulesOperations operations, string name)
{
Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).ExecuteAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Execute a schedule. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ExecuteAsync(this IGlobalSchedulesOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ExecuteWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Execute a schedule. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
public static void BeginExecute(this IGlobalSchedulesOperations operations, string name)
{
Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).BeginExecuteAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Execute a schedule. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginExecuteAsync(this IGlobalSchedulesOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginExecuteWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a schedule's target resource Id. This operation can take a while
/// to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='retargetScheduleProperties'>
/// Properties for retargeting a virtual machine schedule.
/// </param>
public static void Retarget(this IGlobalSchedulesOperations operations, string name, RetargetScheduleProperties retargetScheduleProperties)
{
Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).RetargetAsync(name, retargetScheduleProperties), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a schedule's target resource Id. This operation can take a while
/// to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='retargetScheduleProperties'>
/// Properties for retargeting a virtual machine schedule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RetargetAsync(this IGlobalSchedulesOperations operations, string name, RetargetScheduleProperties retargetScheduleProperties, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.RetargetWithHttpMessagesAsync(name, retargetScheduleProperties, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a schedule's target resource Id. This operation can take a while
/// to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='retargetScheduleProperties'>
/// Properties for retargeting a virtual machine schedule.
/// </param>
public static void BeginRetarget(this IGlobalSchedulesOperations operations, string name, RetargetScheduleProperties retargetScheduleProperties)
{
Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).BeginRetargetAsync(name, retargetScheduleProperties), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a schedule's target resource Id. This operation can take a while
/// to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the schedule.
/// </param>
/// <param name='retargetScheduleProperties'>
/// Properties for retargeting a virtual machine schedule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginRetargetAsync(this IGlobalSchedulesOperations operations, string name, RetargetScheduleProperties retargetScheduleProperties, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginRetargetWithHttpMessagesAsync(name, retargetScheduleProperties, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// List schedules in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Schedule> ListBySubscriptionNext(this IGlobalSchedulesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).ListBySubscriptionNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List schedules in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Schedule>> ListBySubscriptionNextAsync(this IGlobalSchedulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List schedules in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Schedule> ListByResourceGroupNext(this IGlobalSchedulesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IGlobalSchedulesOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List schedules in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Schedule>> ListByResourceGroupNextAsync(this IGlobalSchedulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
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 frmBarcode
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmBarcode() : base()
{
Load += frmBarcode_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_cmdnext;
public System.Windows.Forms.Button cmdnext {
get { return withEventsField_cmdnext; }
set {
if (withEventsField_cmdnext != null) {
withEventsField_cmdnext.Click -= cmdNext_Click;
}
withEventsField_cmdnext = value;
if (withEventsField_cmdnext != null) {
withEventsField_cmdnext.Click += cmdNext_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cndExit;
public System.Windows.Forms.Button cndExit {
get { return withEventsField_cndExit; }
set {
if (withEventsField_cndExit != null) {
withEventsField_cndExit.Click -= cndExit_Click;
}
withEventsField_cndExit = value;
if (withEventsField_cndExit != null) {
withEventsField_cndExit.Click += cndExit_Click;
}
}
}
public System.Windows.Forms.RadioButton _optBarcode_2;
public System.Windows.Forms.RadioButton _optBarcode_1;
private System.Windows.Forms.ListBox withEventsField_lstBarcode;
public System.Windows.Forms.ListBox lstBarcode {
get { return withEventsField_lstBarcode; }
set {
if (withEventsField_lstBarcode != null) {
withEventsField_lstBarcode.DoubleClick -= lstBarcode_DoubleClick;
}
withEventsField_lstBarcode = value;
if (withEventsField_lstBarcode != null) {
withEventsField_lstBarcode.DoubleClick += lstBarcode_DoubleClick;
}
}
}
public System.Windows.Forms.Label _Label2_1;
public System.Windows.Forms.Label lblPrinterType;
public System.Windows.Forms.Label lblPrinter;
public System.Windows.Forms.Label _Label2_0;
public System.Windows.Forms.Label Label1;
//Public WithEvents Label2 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents optBarcode As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
//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(frmBarcode));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdnext = new System.Windows.Forms.Button();
this.cndExit = new System.Windows.Forms.Button();
this._optBarcode_2 = new System.Windows.Forms.RadioButton();
this._optBarcode_1 = new System.Windows.Forms.RadioButton();
this.lstBarcode = new System.Windows.Forms.ListBox();
this._Label2_1 = new System.Windows.Forms.Label();
this.lblPrinterType = new System.Windows.Forms.Label();
this.lblPrinter = new System.Windows.Forms.Label();
this._Label2_0 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
//Me.Label2 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.optBarcode = New Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray(components)
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.Label2, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.optBarcode, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Barcode Printing";
this.ClientSize = new System.Drawing.Size(391, 435);
this.Location = new System.Drawing.Point(3, 29);
this.ControlBox = false;
this.Icon = (System.Drawing.Icon)resources.GetObject("frmBarcode.Icon");
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 = "frmBarcode";
this.cmdnext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdnext.Text = "&Next";
this.cmdnext.Size = new System.Drawing.Size(106, 49);
this.cmdnext.Location = new System.Drawing.Point(272, 376);
this.cmdnext.TabIndex = 9;
this.cmdnext.BackColor = System.Drawing.SystemColors.Control;
this.cmdnext.CausesValidation = true;
this.cmdnext.Enabled = true;
this.cmdnext.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdnext.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdnext.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdnext.TabStop = true;
this.cmdnext.Name = "cmdnext";
this.cndExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cndExit.Text = "E&xit";
this.cndExit.Size = new System.Drawing.Size(106, 49);
this.cndExit.Location = new System.Drawing.Point(8, 376);
this.cndExit.TabIndex = 7;
this.cndExit.BackColor = System.Drawing.SystemColors.Control;
this.cndExit.CausesValidation = true;
this.cndExit.Enabled = true;
this.cndExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cndExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cndExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cndExit.TabStop = true;
this.cndExit.Name = "cndExit";
this._optBarcode_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._optBarcode_2.Text = "Stock Barcode";
this._optBarcode_2.Size = new System.Drawing.Size(133, 40);
this._optBarcode_2.Location = new System.Drawing.Point(9, 69);
this._optBarcode_2.Appearance = System.Windows.Forms.Appearance.Button;
this._optBarcode_2.TabIndex = 2;
this._optBarcode_2.Checked = true;
this._optBarcode_2.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._optBarcode_2.BackColor = System.Drawing.SystemColors.Control;
this._optBarcode_2.CausesValidation = true;
this._optBarcode_2.Enabled = true;
this._optBarcode_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._optBarcode_2.Cursor = System.Windows.Forms.Cursors.Default;
this._optBarcode_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optBarcode_2.TabStop = true;
this._optBarcode_2.Visible = true;
this._optBarcode_2.Name = "_optBarcode_2";
this._optBarcode_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._optBarcode_1.Text = "Shelf Talker";
this._optBarcode_1.Size = new System.Drawing.Size(133, 40);
this._optBarcode_1.Location = new System.Drawing.Point(144, 69);
this._optBarcode_1.Appearance = System.Windows.Forms.Appearance.Button;
this._optBarcode_1.TabIndex = 1;
this._optBarcode_1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this._optBarcode_1.BackColor = System.Drawing.SystemColors.Control;
this._optBarcode_1.CausesValidation = true;
this._optBarcode_1.Enabled = true;
this._optBarcode_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._optBarcode_1.Cursor = System.Windows.Forms.Cursors.Default;
this._optBarcode_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optBarcode_1.TabStop = true;
this._optBarcode_1.Checked = false;
this._optBarcode_1.Visible = true;
this._optBarcode_1.Name = "_optBarcode_1";
this.lstBarcode.Size = new System.Drawing.Size(367, 254);
this.lstBarcode.Location = new System.Drawing.Point(9, 117);
this.lstBarcode.TabIndex = 8;
this.lstBarcode.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lstBarcode.BackColor = System.Drawing.SystemColors.Window;
this.lstBarcode.CausesValidation = true;
this.lstBarcode.Enabled = true;
this.lstBarcode.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstBarcode.IntegralHeight = true;
this.lstBarcode.Cursor = System.Windows.Forms.Cursors.Default;
this.lstBarcode.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.lstBarcode.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstBarcode.Sorted = false;
this.lstBarcode.TabStop = true;
this.lstBarcode.Visible = true;
this.lstBarcode.MultiColumn = true;
this.lstBarcode.ColumnWidth = 367;
this.lstBarcode.Name = "lstBarcode";
this._Label2_1.Text = "Printer Type:";
this._Label2_1.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Label2_1.Size = new System.Drawing.Size(90, 16);
this._Label2_1.Location = new System.Drawing.Point(6, 24);
this._Label2_1.TabIndex = 6;
this._Label2_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label2_1.BackColor = System.Drawing.Color.Transparent;
this._Label2_1.Enabled = true;
this._Label2_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label2_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Label2_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label2_1.UseMnemonic = true;
this._Label2_1.Visible = true;
this._Label2_1.AutoSize = true;
this._Label2_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label2_1.Name = "_Label2_1";
this.lblPrinterType.Text = "Label1";
this.lblPrinterType.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblPrinterType.Size = new System.Drawing.Size(41, 16);
this.lblPrinterType.Location = new System.Drawing.Point(102, 24);
this.lblPrinterType.TabIndex = 5;
this.lblPrinterType.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblPrinterType.BackColor = System.Drawing.Color.Transparent;
this.lblPrinterType.Enabled = true;
this.lblPrinterType.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblPrinterType.Cursor = System.Windows.Forms.Cursors.Default;
this.lblPrinterType.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblPrinterType.UseMnemonic = true;
this.lblPrinterType.Visible = true;
this.lblPrinterType.AutoSize = true;
this.lblPrinterType.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblPrinterType.Name = "lblPrinterType";
this.lblPrinter.Text = "Label1";
this.lblPrinter.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblPrinter.Size = new System.Drawing.Size(41, 16);
this.lblPrinter.Location = new System.Drawing.Point(102, 6);
this.lblPrinter.TabIndex = 4;
this.lblPrinter.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblPrinter.BackColor = System.Drawing.Color.Transparent;
this.lblPrinter.Enabled = true;
this.lblPrinter.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblPrinter.Cursor = System.Windows.Forms.Cursors.Default;
this.lblPrinter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblPrinter.UseMnemonic = true;
this.lblPrinter.Visible = true;
this.lblPrinter.AutoSize = true;
this.lblPrinter.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblPrinter.Name = "lblPrinter";
this._Label2_0.Text = "Printer:";
this._Label2_0.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Label2_0.Size = new System.Drawing.Size(50, 16);
this._Label2_0.Location = new System.Drawing.Point(45, 6);
this._Label2_0.TabIndex = 3;
this._Label2_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label2_0.BackColor = System.Drawing.Color.Transparent;
this._Label2_0.Enabled = true;
this._Label2_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label2_0.Cursor = System.Windows.Forms.Cursors.Default;
this._Label2_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label2_0.UseMnemonic = true;
this._Label2_0.Visible = true;
this._Label2_0.AutoSize = true;
this._Label2_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label2_0.Name = "_Label2_0";
this.Label1.Text = "Select the barcode printing type you require";
this.Label1.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Label1.Size = new System.Drawing.Size(258, 16);
this.Label1.Location = new System.Drawing.Point(12, 45);
this.Label1.TabIndex = 0;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.BackColor = System.Drawing.Color.Transparent;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = true;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.Controls.Add(cmdnext);
this.Controls.Add(cndExit);
this.Controls.Add(_optBarcode_2);
this.Controls.Add(_optBarcode_1);
this.Controls.Add(lstBarcode);
this.Controls.Add(_Label2_1);
this.Controls.Add(lblPrinterType);
this.Controls.Add(lblPrinter);
this.Controls.Add(_Label2_0);
this.Controls.Add(Label1);
//Me.Label2.SetIndex(_Label2_1, CType(1, Short))
//Me.Label2.SetIndex(_Label2_0, CType(0, Short))
//Me.optBarcode.SetIndex(_optBarcode_2, CType(2, Short))
//Me.optBarcode.SetIndex(_optBarcode_1, CType(1, Short))
//CType(Me.optBarcode, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.Label2, System.ComponentModel.ISupportInitialize).EndInit()
this.ResumeLayout(false);
this.PerformLayout();
}
#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.Text;
using System.Diagnostics;
namespace System
{
internal static class UriHelper
{
internal static readonly char[] s_hexUpperChars = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
// http://host/Path/Path/File?Query is the base of
// - http://host/Path/Path/File/ ... (those "File" words may be different in semantic but anyway)
// - http://host/Path/Path/#Fragment
// - http://host/Path/Path/?Query
// - http://host/Path/Path/MoreDir/ ...
// - http://host/Path/Path/OtherFile?Query
// - http://host/Path/Path/Fl
// - http://host/Path/Path/
//
// It is not a base for
// - http://host/Path/Path (that last "Path" is not considered as a directory)
// - http://host/Path/Path?Query
// - http://host/Path/Path#Fragment
// - http://host/Path/Path2/
// - http://host/Path/Path2/MoreDir
// - http://host/Path/File
//
// ASSUMES that strings like http://host/Path/Path/MoreDir/../../ have been canonicalized before going to this method.
// ASSUMES that back slashes already have been converted if applicable.
//
internal static unsafe bool TestForSubPath(char* selfPtr, ushort selfLength, char* otherPtr, ushort otherLength,
bool ignoreCase)
{
ushort i = 0;
char chSelf;
char chOther;
bool AllSameBeforeSlash = true;
for (; i < selfLength && i < otherLength; ++i)
{
chSelf = *(selfPtr + i);
chOther = *(otherPtr + i);
if (chSelf == '?' || chSelf == '#')
{
// survived so far and selfPtr does not have any more path segments
return true;
}
// If selfPtr terminates a path segment, so must otherPtr
if (chSelf == '/')
{
if (chOther != '/')
{
// comparison has failed
return false;
}
// plus the segments must be the same
if (!AllSameBeforeSlash)
{
// comparison has failed
return false;
}
//so far so good
AllSameBeforeSlash = true;
continue;
}
// if otherPtr terminates then selfPtr must not have any more path segments
if (chOther == '?' || chOther == '#')
{
break;
}
if (!ignoreCase)
{
if (chSelf != chOther)
{
AllSameBeforeSlash = false;
}
}
else
{
if (char.ToLowerInvariant(chSelf) != char.ToLowerInvariant(chOther))
{
AllSameBeforeSlash = false;
}
}
}
// If self is longer then it must not have any more path segments
for (; i < selfLength; ++i)
{
if ((chSelf = *(selfPtr + i)) == '?' || chSelf == '#')
{
return true;
}
if (chSelf == '/')
{
return false;
}
}
//survived by getting to the end of selfPtr
return true;
}
// - forceX characters are always escaped if found
// - rsvd character will remain unescaped
//
// start - starting offset from input
// end - the exclusive ending offset in input
// destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output.
//
// In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos
//
// Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos
//
private const short c_MaxAsciiCharsReallocate = 40;
private const short c_MaxUnicodeCharsReallocate = 40;
private const short c_MaxUTF_8BytesPerUnicodeChar = 4;
private const short c_EncodedCharsPerByte = 3;
internal static unsafe char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos,
bool isUriString, char force1, char force2, char rsvd)
{
if (end - start >= Uri.c_MaxUriBufferSize)
throw new UriFormatException(SR.net_uri_SizeLimit);
int i = start;
int prevInputPos = start;
byte* bytes = stackalloc byte[c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160
fixed (char* pStr = input)
{
for (; i < end; ++i)
{
char ch = pStr[i];
// a Unicode ?
if (ch > '\x7F')
{
short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate - 1);
short count = 1;
for (; count < maxSize && pStr[i + count] > '\x7f'; ++count)
;
// Is the last a high surrogate?
if (pStr[i + count - 1] >= 0xD800 && pStr[i + count - 1] <= 0xDBFF)
{
// Should be a rare case where the app tries to feed an invalid Unicode surrogates pair
if (count == 1 || count == end - i)
throw new UriFormatException(SR.net_uri_BadString);
// need to grab one more char as a Surrogate except when it's a bogus input
++count;
}
dest = EnsureDestinationSize(pStr, dest, i,
(short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte),
c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte,
ref destPos, prevInputPos);
short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr + i, count, bytes,
c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar);
// This is the only exception that built in UriParser can throw after a Uri ctor.
// Should not happen unless the app tries to feed an invalid Unicode String
if (numberOfBytes == 0)
throw new UriFormatException(SR.net_uri_BadString);
i += (count - 1);
for (count = 0; count < numberOfBytes; ++count)
EscapeAsciiChar((char)bytes[count], dest, ref destPos);
prevInputPos = i + 1;
}
else if (ch == '%' && rsvd == '%')
{
// Means we don't reEncode '%' but check for the possible escaped sequence
dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
if (i + 2 < end && EscapedAscii(pStr[i + 1], pStr[i + 2]) != Uri.c_DummyChar)
{
// leave it escaped
dest[destPos++] = '%';
dest[destPos++] = pStr[i + 1];
dest[destPos++] = pStr[i + 2];
i += 2;
}
else
{
EscapeAsciiChar('%', dest, ref destPos);
}
prevInputPos = i + 1;
}
else if (ch == force1 || ch == force2)
{
dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
EscapeAsciiChar(ch, dest, ref destPos);
prevInputPos = i + 1;
}
else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch)))
{
dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte,
c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos);
EscapeAsciiChar(ch, dest, ref destPos);
prevInputPos = i + 1;
}
}
if (prevInputPos != i)
{
// need to fill up the dest array ?
if (prevInputPos != start || dest != null)
dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos);
}
}
return dest;
}
//
// ensure destination array has enough space and contains all the needed input stuff
//
private static unsafe char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos,
short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos)
{
if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd)
{
// allocating or reallocating array by ensuring enough space based on maxCharsToAdd.
char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars];
if ((object)dest != null && destPos != 0)
Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1);
dest = newresult;
}
// ensuring we copied everything form the input string left before last escaping
while (prevInputPos != currentInputPos)
dest[destPos++] = pStr[prevInputPos++];
return dest;
}
//
// This method will assume that any good Escaped Sequence will be unescaped in the output
// - Assumes Dest.Length - detPosition >= end-start
// - UnescapeLevel controls various modes of operation
// - Any "bad" escape sequence will remain as is or '%' will be escaped.
// - destPosition tells the starting index in dest for placing the result.
// On return destPosition tells the last character + 1 position in the "dest" array.
// - The control chars and chars passed in rsdvX parameters may be re-escaped depending on UnescapeLevel
// - It is a RARE case when Unescape actually needs escaping some characters mentioned above.
// For this reason it returns a char[] that is usually the same ref as the input "dest" value.
//
internal static unsafe char[] UnescapeString(string input, int start, int end, char[] dest,
ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax,
bool isQuery)
{
fixed (char* pStr = input)
{
return UnescapeString(pStr, start, end, dest, ref destPosition, rsvd1, rsvd2, rsvd3, unescapeMode,
syntax, isQuery);
}
}
internal static unsafe char[] UnescapeString(char* pStr, int start, int end, char[] dest, ref int destPosition,
char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax, bool isQuery)
{
byte[] bytes = null;
byte escapedReallocations = 0;
bool escapeReserved = false;
int next = start;
bool iriParsing = Uri.IriParsingStatic(syntax)
&& ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.EscapeUnescape);
while (true)
{
// we may need to re-pin dest[]
fixed (char* pDest = dest)
{
if ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.CopyOnly)
{
while (start < end)
pDest[destPosition++] = pStr[start++];
return dest;
}
while (true)
{
char ch = (char)0;
for (; next < end; ++next)
{
if ((ch = pStr[next]) == '%')
{
if ((unescapeMode & UnescapeMode.Unescape) == 0)
{
// re-escape, don't check anything else
escapeReserved = true;
}
else if (next + 2 < end)
{
ch = EscapedAscii(pStr[next + 1], pStr[next + 2]);
// Unescape a good sequence if full unescape is requested
if (unescapeMode >= UnescapeMode.UnescapeAll)
{
if (ch == Uri.c_DummyChar)
{
if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow)
{
// Should be a rare case where the app tries to feed an invalid escaped sequence
throw new UriFormatException(SR.net_uri_BadString);
}
continue;
}
}
// re-escape % from an invalid sequence
else if (ch == Uri.c_DummyChar)
{
if ((unescapeMode & UnescapeMode.Escape) != 0)
escapeReserved = true;
else
continue; // we should throw instead but since v1.0 would just print '%'
}
// Do not unescape '%' itself unless full unescape is requested
else if (ch == '%')
{
next += 2;
continue;
}
// Do not unescape a reserved char unless full unescape is requested
else if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3)
{
next += 2;
continue;
}
// Do not unescape a dangerous char unless it's V1ToStringFlags mode
else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && IsNotSafeForUnescape(ch))
{
next += 2;
continue;
}
else if (iriParsing && ((ch <= '\x9F' && IsNotSafeForUnescape(ch)) ||
(ch > '\x9F' && !IriHelper.CheckIriUnicodeRange(ch, isQuery))))
{
// check if unenscaping gives a char outside iri range
// if it does then keep it escaped
next += 2;
continue;
}
// unescape escaped char or escape %
break;
}
else if (unescapeMode >= UnescapeMode.UnescapeAll)
{
if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow)
{
// Should be a rare case where the app tries to feed an invalid escaped sequence
throw new UriFormatException(SR.net_uri_BadString);
}
// keep a '%' as part of a bogus sequence
continue;
}
else
{
escapeReserved = true;
}
// escape (escapeReserved==true) or otherwise unescape the sequence
break;
}
else if ((unescapeMode & (UnescapeMode.Unescape | UnescapeMode.UnescapeAll))
== (UnescapeMode.Unescape | UnescapeMode.UnescapeAll))
{
continue;
}
else if ((unescapeMode & UnescapeMode.Escape) != 0)
{
// Could actually escape some of the characters
if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3)
{
// found an unescaped reserved character -> escape it
escapeReserved = true;
break;
}
else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0
&& (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F')))
{
// found an unescaped reserved character -> escape it
escapeReserved = true;
break;
}
}
}
//copy off previous characters from input
while (start < next)
pDest[destPosition++] = pStr[start++];
if (next != end)
{
if (escapeReserved)
{
//escape that char
// Since this should be _really_ rare case, reallocate with constant size increase of 30 rsvd-type characters.
if (escapedReallocations == 0)
{
escapedReallocations = 30;
char[] newDest = new char[dest.Length + escapedReallocations * 3];
fixed (char* pNewDest = &newDest[0])
{
for (int i = 0; i < destPosition; ++i)
pNewDest[i] = pDest[i];
}
dest = newDest;
// re-pin new dest[] array
goto dest_fixed_loop_break;
}
else
{
--escapedReallocations;
EscapeAsciiChar(pStr[next], dest, ref destPosition);
escapeReserved = false;
start = ++next;
continue;
}
}
// unescaping either one Ascii or possibly multiple Unicode
if (ch <= '\x7F')
{
//ASCII
dest[destPosition++] = ch;
next += 3;
start = next;
continue;
}
// Unicode
int byteCount = 1;
// lazy initialization of max size, will reuse the array for next sequences
if ((object)bytes == null)
bytes = new byte[end - next];
bytes[0] = (byte)ch;
next += 3;
while (next < end)
{
// Check on exit criterion
if ((ch = pStr[next]) != '%' || next + 2 >= end)
break;
// already made sure we have 3 characters in str
ch = EscapedAscii(pStr[next + 1], pStr[next + 2]);
//invalid hex sequence ?
if (ch == Uri.c_DummyChar)
break;
// character is not part of a UTF-8 sequence ?
else if (ch < '\x80')
break;
else
{
//a UTF-8 sequence
bytes[byteCount++] = (byte)ch;
next += 3;
}
}
Encoding noFallbackCharUTF8 = Encoding.GetEncoding(
Encoding.UTF8.CodePage,
new EncoderReplacementFallback(""),
new DecoderReplacementFallback(""));
char[] unescapedChars = new char[bytes.Length];
int charCount = noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0);
start = next;
// match exact bytes
// Do not unescape chars not allowed by Iri
// need to check for invalid utf sequences that may not have given any chars
MatchUTF8Sequence(pDest, dest, ref destPosition, unescapedChars, charCount, bytes,
byteCount, isQuery, iriParsing);
}
if (next == end)
goto done;
}
dest_fixed_loop_break:;
}
}
done: return dest;
}
//
// Need to check for invalid utf sequences that may not have given any chars.
// We got the unescaped chars, we then re-encode them and match off the bytes
// to get the invalid sequence bytes that we just copy off
//
internal static unsafe void MatchUTF8Sequence(char* pDest, char[] dest, ref int destOffset, char[] unescapedChars,
int charCount, byte[] bytes, int byteCount, bool isQuery, bool iriParsing)
{
int count = 0;
fixed (char* unescapedCharsPtr = unescapedChars)
{
for (int j = 0; j < charCount; ++j)
{
bool isHighSurr = char.IsHighSurrogate(unescapedCharsPtr[j]);
byte[] encodedBytes = Encoding.UTF8.GetBytes(unescapedChars, j, isHighSurr ? 2 : 1);
int encodedBytesLength = encodedBytes.Length;
// we have to keep unicode chars outside Iri range escaped
bool inIriRange = false;
if (iriParsing)
{
if (!isHighSurr)
inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], isQuery);
else
{
bool surrPair = false;
inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], unescapedChars[j + 1],
ref surrPair, isQuery);
}
}
while (true)
{
// Escape any invalid bytes that were before this character
while (bytes[count] != encodedBytes[0])
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
// check if all bytes match
bool allBytesMatch = true;
int k = 0;
for (; k < encodedBytesLength; ++k)
{
if (bytes[count + k] != encodedBytes[k])
{
allBytesMatch = false;
break;
}
}
if (allBytesMatch)
{
count += encodedBytesLength;
if (iriParsing)
{
if (!inIriRange)
{
// need to keep chars not allowed as escaped
for (int l = 0; l < encodedBytes.Length; ++l)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
EscapeAsciiChar((char)encodedBytes[l], dest, ref destOffset);
}
}
else if (!UriHelper.IsBidiControlCharacter(unescapedCharsPtr[j]) || !UriParser.DontKeepUnicodeBidiFormattingCharacters)
{
//copy chars
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
pDest[destOffset++] = unescapedCharsPtr[j];
if (isHighSurr)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
pDest[destOffset++] = unescapedCharsPtr[j + 1];
}
}
}
else
{
//copy chars
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
pDest[destOffset++] = unescapedCharsPtr[j];
if (isHighSurr)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
pDest[destOffset++] = unescapedCharsPtr[j + 1];
}
}
break; // break out of while (true) since we've matched this char bytes
}
else
{
// copy bytes till place where bytes don't match
for (int l = 0; l < k; ++l)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
}
}
if (isHighSurr) j++;
}
}
// Include any trailing invalid sequences
while (count < byteCount)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
}
internal static void EscapeAsciiChar(char ch, char[] to, ref int pos)
{
to[pos++] = '%';
to[pos++] = s_hexUpperChars[(ch & 0xf0) >> 4];
to[pos++] = s_hexUpperChars[ch & 0xf];
}
internal static char EscapedAscii(char digit, char next)
{
if (!(((digit >= '0') && (digit <= '9'))
|| ((digit >= 'A') && (digit <= 'F'))
|| ((digit >= 'a') && (digit <= 'f'))))
{
return Uri.c_DummyChar;
}
int res = (digit <= '9')
? ((int)digit - (int)'0')
: (((digit <= 'F')
? ((int)digit - (int)'A')
: ((int)digit - (int)'a'))
+ 10);
if (!(((next >= '0') && (next <= '9'))
|| ((next >= 'A') && (next <= 'F'))
|| ((next >= 'a') && (next <= 'f'))))
{
return Uri.c_DummyChar;
}
return (char)((res << 4) + ((next <= '9')
? ((int)next - (int)'0')
: (((next <= 'F')
? ((int)next - (int)'A')
: ((int)next - (int)'a'))
+ 10)));
}
internal const string RFC3986ReservedMarks = @";/?:@&=+$,#[]!'()*";
private const string RFC2396ReservedMarks = @";/?:@&=+$,";
private const string RFC3986UnreservedMarks = @"-_.~";
private const string RFC2396UnreservedMarks = @"-_.~*'()!";
private const string AdditionalUnsafeToUnescape = @"%\#";// While not specified as reserved, these are still unsafe to unescape.
// When unescaping in safe mode, do not unescape the RFC 3986 reserved set:
// gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
//
// In addition, do not unescape the following unsafe characters:
// excluded = "%" / "\"
//
// This implementation used to use the following variant of the RFC 2396 reserved set.
// That behavior is now disabled by default, and is controlled by a UriSyntax property.
// reserved = ";" | "/" | "?" | "@" | "&" | "=" | "+" | "$" | ","
// excluded = control | "#" | "%" | "\"
internal static bool IsNotSafeForUnescape(char ch)
{
if (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F'))
{
return true;
}
else if (UriParser.DontEnableStrictRFC3986ReservedCharacterSets)
{
if ((ch != ':' && (RFC2396ReservedMarks.IndexOf(ch) >= 0) || (AdditionalUnsafeToUnescape.IndexOf(ch) >= 0)))
{
return true;
}
}
else if ((RFC3986ReservedMarks.IndexOf(ch) >= 0) || (AdditionalUnsafeToUnescape.IndexOf(ch) >= 0))
{
return true;
}
return false;
}
private static unsafe bool IsReservedUnreservedOrHash(char c)
{
if (IsUnreserved(c))
{
return true;
}
return (RFC3986ReservedMarks.IndexOf(c) >= 0);
}
internal static unsafe bool IsUnreserved(char c)
{
if (UriHelper.IsAsciiLetterOrDigit(c))
{
return true;
}
return (RFC3986UnreservedMarks.IndexOf(c) >= 0);
}
internal static bool Is3986Unreserved(char c)
{
if (UriHelper.IsAsciiLetterOrDigit(c))
{
return true;
}
return (RFC3986UnreservedMarks.IndexOf(c) >= 0);
}
//
// Is this a gen delim char from RFC 3986
//
internal static bool IsGenDelim(char ch)
{
return (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@');
}
internal static readonly char[] s_WSchars = new char[] { ' ', '\n', '\r', '\t' };
internal static bool IsLWS(char ch)
{
return (ch <= ' ') && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t');
}
//Only consider ASCII characters
internal static bool IsAsciiLetter(char character)
{
return (character >= 'a' && character <= 'z') ||
(character >= 'A' && character <= 'Z');
}
internal static bool IsAsciiLetterOrDigit(char character)
{
return IsAsciiLetter(character) || (character >= '0' && character <= '9');
}
//
// Is this a Bidirectional control char.. These get stripped
//
internal static bool IsBidiControlCharacter(char ch)
{
return (ch == '\u200E' /*LRM*/ || ch == '\u200F' /*RLM*/ || ch == '\u202A' /*LRE*/ ||
ch == '\u202B' /*RLE*/ || ch == '\u202C' /*PDF*/ || ch == '\u202D' /*LRO*/ ||
ch == '\u202E' /*RLO*/);
}
//
// Strip Bidirectional control characters from this string
//
internal static unsafe string StripBidiControlCharacter(char* strToClean, int start, int length)
{
if (length <= 0) return "";
char[] cleanStr = new char[length];
int count = 0;
for (int i = 0; i < length; ++i)
{
char c = strToClean[start + i];
if (c < '\u200E' || c > '\u202E' || !IsBidiControlCharacter(c))
{
cleanStr[count++] = c;
}
}
return new string(cleanStr, 0, count);
}
}
}
| |
/*
* Copyright (c) 2010, www.wojilu.com. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Web.Mvc.Attr;
using wojilu.Apps.Reader.Interface;
using wojilu.Apps.Reader.Service;
using wojilu.Apps.Reader.Domain;
using wojilu.Members.Users.Domain;
using wojilu.Common.AppBase.Interface;
using wojilu.Common.AppBase;
namespace wojilu.Web.Controller.Reader.Admin {
[App( typeof( ReaderApp ) )]
public class SubscriptionController : ControllerBase {
public IFeedCategoryService categoryService { get; set; }
public IFeedSourceService feedService { get; set; }
public ISubscriptionService subscriptionService { get; set; }
public IFeedEntryService entryService { get; set; }
public SubscriptionController() {
categoryService = new FeedCategoryService();
feedService = new FeedSourceService();
subscriptionService = new SubscriptionService();
entryService = new FeedEntryService();
base.HideLayout( typeof( Reader.LayoutController ) );
}
public override void Layout() {
}
public void Index() {
List<Subscription> list =subscriptionService.GetByApp( ctx.app.Id );
bindSubscribeList( list );
set( "sortAction", to( SaveSort ) );
set( "addSubscriptionLink", to( Add ) );
}
[HttpPost, DbTransaction]
public virtual void SaveSort() {
int id = ctx.PostInt( "id" );
String cmd = ctx.Post( "cmd" );
Subscription subscription = subscriptionService.GetById( id );
List<Subscription> list = subscriptionService.GetByApp( ctx.app.Id );
if (cmd == "up") {
new SortUtil<Subscription>( subscription, list ).MoveUp();
echoRedirect( "ok" );
}
else if (cmd == "down") {
new SortUtil<Subscription>( subscription, list ).MoveDown();
echoRedirect( "ok" );
}
else {
echoError( lang( "exUnknowCmd" ) );
}
}
public void Add() {
List<FeedCategory> categories = categoryService.GetByApp( ctx.app.Id );
if (categories.Count == 0) {
echoRedirect( "please add a category first", new FeedCategoryController().Add );
return;
}
target( Create );
dropList( "CategoryId", categories, "Name=Id", categories[0].Id );
}
[HttpPost, DbTransaction]
public void Create() {
String rssLink = ctx.Post( "Link" );
if (strUtil.IsNullOrEmpty( rssLink )) {
echoError( "rss url can not be empty" );
return;
}
int categoryId = ctx.PostInt( "CategoryId" );
FeedCategory category = categoryService.GetById( categoryId );
String name = ctx.Post( "Name" );
Subscription s= feedService.Create( rssLink, category, name, 0, (User)ctx.owner.obj );
redirect( Show, s.Id );
}
public void Edit( int id ) {
Subscription sf = subscriptionService.GetById( id );
if (sf == null) {
echoError( "feed is not exists" );
return;
}
List<FeedCategory> categories = categoryService.GetByApp( ctx.app.Id );
bindEdit( sf, categories );
target( Update, id );
}
[HttpPost, DbTransaction]
public void Update( int id ) {
Subscription sf = subscriptionService.GetById( id );
if (sf == null) {
echoError( "feed is not exists" );
return;
}
sf.Name = ctx.Post( "Name" );
//sf.OrderId = ctx.PostInt( "OrderId" );
int categoryId = ctx.PostInt( "CategoryId" );
sf.Category = new FeedCategory( categoryId );
subscriptionService.Update( sf );
redirect( Index );
}
[HttpDelete, DbTransaction]
public void Delete( int id ) {
Subscription sf = subscriptionService.GetById( id );
if (sf == null) {
echoError( "feed is not exists" );
return;
}
subscriptionService.Delete( sf );
echoRedirect( lang( "opok" ) );
}
private void bindSubscribeList( List<Subscription> list ) {
IBlock block = getBlock( "list" );
foreach (Subscription sf in list) {
block.Set( "feed.Id", sf.Id );
block.Set( "feed.OrderId", sf.OrderId );
block.Set( "feed.Name", sf.Name );
block.Set( "feed.Title", sf.FeedSource.Title );
block.Set( "feed.LinkEdit", to( Edit, sf.Id ) );
block.Set( "feed.LinkDelete", to( Delete, sf.Id ) );
block.Next();
}
}
private void bindEdit( Subscription sf, List<FeedCategory> categories ) {
set( "feed.Title", sf.FeedSource.Title );
set( "feed.Name", sf.Name );
set( "feed.RssLink", sf.FeedSource.FeedLink );
set( "feed.OrderId", sf.OrderId.ToString() );
dropList( "CategoryId", categories, "Name=Id", sf.Category.Id );
}
public void Show( int id ) {
Subscription s = subscriptionService.GetById( id );
DataPage<FeedEntry> list = entryService.GetPage( s.FeedSource.Id );
bindFeedInfo( s.FeedSource );
bindFeedItem( list );
}
private void bindFeedItem( DataPage<FeedEntry> list ) {
IBlock itemBlock = getBlock( "item" );
foreach (FeedEntry item in list.Results) {
itemBlock.Set( "item.Title", item.Title );
itemBlock.Set( "item.Link", to( new EntryController().Show, item.Id ) );
itemBlock.Set( "item.PubDate", item.PubDate );
itemBlock.Set( "item.Description", item.Abstract );
itemBlock.Next();
}
set( "page", list.PageBar );
}
private void bindFeedInfo( FeedSource f ) {
set( "feed.Title", f.Title );
set( "feed.Link", f.Link );
set( "feed.RssLink", f.FeedLink );
set( "feed.LastRefreshTime", f.LastRefreshTime );
//set( "feed.MemberListUrl", to( Users, f.Id ) );
set( "feed.UserCount", f.UserCount );
}
}
}
| |
//
// Job.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Hyena.Jobs
{
public enum JobState {
None,
Scheduled,
Running,
Paused,
Cancelled,
Completed
};
public class Job
{
public event EventHandler Updated;
public event EventHandler Finished;
public event EventHandler CancelRequested;
private int update_freeze_ref;
private JobState state = JobState.None;
private ManualResetEvent pause_event;
private DateTime created_at = DateTime.Now;
private TimeSpan run_time = TimeSpan.Zero;
private Object sync = new Object ();
public bool IsCancelRequested { get; private set; }
#region Internal Properties
internal bool IsScheduled {
get { return state == JobState.Scheduled; }
}
internal bool IsRunning {
get { return state == JobState.Running; }
}
internal bool IsPaused {
get { return state == JobState.Paused; }
}
public bool IsFinished {
get {
lock (sync) {
return state == JobState.Cancelled || state == JobState.Completed;
}
}
}
internal DateTime CreatedAt {
get { return created_at; }
}
internal TimeSpan RunTime {
get { return run_time; }
}
#endregion
#region Scheduler Methods
internal void Start ()
{
Log.Debug ("Starting", Title);
lock (sync) {
if (state != JobState.Scheduled && state != JobState.Paused) {
Log.DebugFormat ("Job {0} in {1} state is not runnable", Title, state);
return;
}
State = JobState.Running;
if (pause_event != null) {
pause_event.Set ();
}
RunJob ();
}
}
internal void Cancel ()
{
lock (sync) {
if (!IsFinished) {
IsCancelRequested = true;
State = JobState.Cancelled;
EventHandler handler = CancelRequested;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
}
Log.Debug ("Canceled", Title);
}
internal void Preempt ()
{
Log.Debug ("Preempting", Title);
Pause (false);
}
internal bool Pause ()
{
Log.Debug ("Pausing ", Title);
return Pause (true);
}
private bool Pause (bool unschedule)
{
lock (sync) {
if (IsFinished) {
Log.DebugFormat ("Job {0} in {1} state is not pausable", Title, state);
return false;
}
State = unschedule ? JobState.Paused : JobState.Scheduled;
if (pause_event != null) {
pause_event.Reset ();
}
}
return true;
}
#endregion
private string title;
private string status;
private string [] icon_names;
private double progress;
#region Public Properties
public string Title {
get { return title; }
set {
title = value;
OnUpdated ();
}
}
public string Status {
get { return status; }
set {
status = value;
OnUpdated ();
}
}
public double Progress {
get { return progress; }
set {
progress = Math.Max (0.0, Math.Min (1.0, value));
OnUpdated ();
}
}
public string [] IconNames {
get { return icon_names; }
set {
if (value != null) {
icon_names = value;
OnUpdated ();
}
}
}
public bool IsBackground { get; set; }
public bool CanCancel { get; set; }
public string CancelMessage { get; set; }
public bool DelayShow { get; set; }
public PriorityHints PriorityHints { get; set; }
// Causes runtime method-not-found error in mono 2.0.1
//public IEnumerable<Resource> Resources { get; protected set; }
internal Resource [] Resources;
public JobState State {
get { return state; }
internal set {
state = value;
OnUpdated ();
}
}
public void SetResources (params Resource [] resources)
{
Resources = resources ?? new Resource [0];
}
#endregion
#region Constructor
public Job () : this (null, PriorityHints.None)
{
}
public Job (string title, PriorityHints hints, params Resource [] resources)
{
Title = title;
PriorityHints = hints;
SetResources (resources);
}
#endregion
#region Abstract Methods
protected virtual void RunJob ()
{
}
#endregion
#region Protected Methods
public void Update (string title, string status, double progress)
{
Title = title;
Status = status;
Progress = progress;
}
protected void FreezeUpdate ()
{
System.Threading.Interlocked.Increment (ref update_freeze_ref);
}
protected void ThawUpdate (bool raiseUpdate)
{
System.Threading.Interlocked.Decrement (ref update_freeze_ref);
if (raiseUpdate) {
OnUpdated ();
}
}
protected void OnUpdated ()
{
if (update_freeze_ref != 0) {
return;
}
EventHandler handler = Updated;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
public void YieldToScheduler ()
{
if (IsPaused || IsScheduled) {
if (pause_event == null) {
pause_event = new ManualResetEvent (false);
}
pause_event.WaitOne ();
}
}
protected void OnFinished ()
{
Log.Debug ("Finished", Title);
pause_event = null;
if (state != JobState.Cancelled) {
State = JobState.Completed;
}
EventHandler handler = Finished;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
#endregion
internal bool HasScheduler { get; set; }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Options;
namespace OrchardCore.ResourceManagement
{
public class ResourceManager : IResourceManager
{
private readonly Dictionary<ResourceTypeName, RequireSettings> _required = new Dictionary<ResourceTypeName, RequireSettings>();
private readonly Dictionary<string, ResourceRequiredContext[]> _builtResources;
private readonly IFileVersionProvider _fileVersionProvider;
private ResourceManifest _dynamicManifest;
private List<LinkEntry> _links;
private Dictionary<string, MetaEntry> _metas;
private List<IHtmlContent> _headScripts;
private List<IHtmlContent> _footScripts;
private List<IHtmlContent> _styles;
private HashSet<string> _localScripts;
private HashSet<string> _localStyles;
private readonly ResourceManagementOptions _options;
public ResourceManager(
IOptions<ResourceManagementOptions> options,
IFileVersionProvider fileVersionProvider)
{
_options = options.Value;
_fileVersionProvider = fileVersionProvider;
_builtResources = new Dictionary<string, ResourceRequiredContext[]>(StringComparer.OrdinalIgnoreCase);
}
public ResourceManifest InlineManifest => _dynamicManifest ??= new ResourceManifest();
public RequireSettings RegisterResource(string resourceType, string resourceName)
{
if (resourceType == null)
{
return ThrowArgumentNullException<RequireSettings>(nameof(resourceType));
}
if (resourceName == null)
{
return ThrowArgumentNullException<RequireSettings>(nameof(resourceName));
}
var key = new ResourceTypeName(resourceType, resourceName);
if (!_required.TryGetValue(key, out var settings))
{
settings = new RequireSettings(_options)
{
Type = resourceType,
Name = resourceName
};
_required[key] = settings;
}
_builtResources[resourceType] = null;
return settings;
}
public RequireSettings RegisterUrl(string resourceType, string resourcePath, string resourceDebugPath)
{
if (resourceType == null)
{
return ThrowArgumentNullException<RequireSettings>(nameof(resourceType));
}
if (resourcePath == null)
{
return ThrowArgumentNullException<RequireSettings>(nameof(resourcePath));
}
// ~/ ==> convert to absolute path (e.g. /orchard/..)
if (resourcePath.StartsWith("~/", StringComparison.Ordinal))
{
resourcePath = _options.ContentBasePath + resourcePath.Substring(1);
}
if (resourceDebugPath != null && resourceDebugPath.StartsWith("~/", StringComparison.Ordinal))
{
resourceDebugPath = _options.ContentBasePath + resourceDebugPath.Substring(1);
}
return RegisterResource(
resourceType,
GetResourceKey(resourcePath, resourceDebugPath)).Define(d => d.SetUrl(resourcePath, resourceDebugPath));
}
public void RegisterHeadScript(IHtmlContent script)
{
if (_headScripts == null)
{
_headScripts = new List<IHtmlContent>();
}
_headScripts.Add(script);
}
public void RegisterFootScript(IHtmlContent script)
{
if (_footScripts == null)
{
_footScripts = new List<IHtmlContent>();
}
_footScripts.Add(script);
}
public void RegisterStyle(IHtmlContent style)
{
if (_styles == null)
{
_styles = new List<IHtmlContent>();
}
_styles.Add(style);
}
public void NotRequired(string resourceType, string resourceName)
{
if (resourceType == null)
{
ThrowArgumentNullException(nameof(resourceType));
return;
}
if (resourceName == null)
{
ThrowArgumentNullException(nameof(resourceName));
return;
}
var key = new ResourceTypeName(resourceType, resourceName);
_builtResources[resourceType] = null;
_required.Remove(key);
}
public ResourceDefinition FindResource(RequireSettings settings)
{
return FindResource(settings, true);
}
private ResourceDefinition FindResource(RequireSettings settings, bool resolveInlineDefinitions)
{
// find the resource with the given type and name
// that has at least the given version number. If multiple,
// return the resource with the greatest version number.
// If not found and an inlineDefinition is given, define the resource on the fly
// using the action.
var name = settings.Name ?? "";
var type = settings.Type;
var stream = _options.ResourceManifests.SelectMany(x => x.GetResources(type));
var resource = FindMatchingResource(stream, settings, name);
if (resource == null && _dynamicManifest != null)
{
stream = _dynamicManifest.GetResources(type);
resource = FindMatchingResource(stream, settings, name);
}
if (resolveInlineDefinitions && resource == null)
{
// Does not seem to exist, but it's possible it is being
// defined by a Define() from a RequireSettings somewhere.
if (ResolveInlineDefinitions(settings.Type))
{
// if any were defined, now try to find it
resource = FindResource(settings, false);
}
}
return resource;
}
private ResourceDefinition FindMatchingResource(
IEnumerable<KeyValuePair<string, IList<ResourceDefinition>>> stream,
RequireSettings settings,
string name)
{
Version lower = null;
Version upper = null;
if (!String.IsNullOrEmpty(settings.Version))
{
// Specific version, filter
lower = GetLowerBoundVersion(settings.Version);
upper = GetUpperBoundVersion(settings.Version);
}
ResourceDefinition resource = null;
foreach (var r in stream)
{
if (String.Equals(r.Key, name, StringComparison.OrdinalIgnoreCase))
{
foreach (var resourceDefinition in r.Value)
{
var version = resourceDefinition.Version != null
? new Version(resourceDefinition.Version)
: null;
if (lower != null)
{
if (lower > version || version >= upper)
{
continue;
}
}
// Use the highest version of all matches
if (resource == null
|| (resourceDefinition.Version != null && new Version(resource.Version) < version))
{
resource = resourceDefinition;
}
}
}
}
return resource;
}
/// <summary>
/// Returns the upper bound value of a required version number.
/// For instance, 3.1.0 returns 3.1.1, 4 returns 5.0.0, 6.1 returns 6.2.0
/// </summary>
private Version GetUpperBoundVersion(string minimumVersion)
{
if (!Version.TryParse(minimumVersion, out var version))
{
// Is is a single number?
if (Int32.TryParse(minimumVersion, out var major))
{
return new Version(major + 1, 0, 0);
}
}
if (version.Build != -1)
{
return new Version(version.Major, version.Minor, version.Build + 1);
}
if (version.Minor != -1)
{
return new Version(version.Major, version.Minor + 1, 0);
}
return version;
}
/// <summary>
/// Returns the lower bound value of a required version number.
/// For instance, 3.1.0 returns 3.1.0, 4 returns 4.0.0, 6.1 returns 6.1.0
/// </summary>
private Version GetLowerBoundVersion(string minimumVersion)
{
if (!Version.TryParse(minimumVersion, out var version))
{
// Is is a single number?
if (Int32.TryParse(minimumVersion, out var major))
{
return new Version(major, 0, 0);
}
}
return version;
}
private bool ResolveInlineDefinitions(string resourceType)
{
var anyWereDefined = false;
foreach (var settings in ResolveRequiredResources(resourceType))
{
if (settings.InlineDefinition == null)
{
continue;
}
// defining it on the fly
var resource = FindResource(settings, false);
if (resource == null)
{
// does not already exist, so define it
resource = InlineManifest.DefineResource(resourceType, settings.Name).SetBasePath(settings.BasePath);
anyWereDefined = true;
}
settings.InlineDefinition(resource);
settings.InlineDefinition = null;
}
return anyWereDefined;
}
private IEnumerable<RequireSettings> ResolveRequiredResources(string resourceType)
{
foreach (var (key, value) in _required)
{
if (key.Type == resourceType)
{
yield return value;
}
}
}
public IEnumerable<LinkEntry> GetRegisteredLinks() => DoGetRegisteredLinks();
private List<LinkEntry> DoGetRegisteredLinks()
{
return _links ?? EmptyList<LinkEntry>.Instance;
}
public IEnumerable<MetaEntry> GetRegisteredMetas() => DoGetRegisteredMetas();
private Dictionary<string, MetaEntry>.ValueCollection DoGetRegisteredMetas()
{
return _metas?.Values ?? EmptyValueCollection<MetaEntry>.Instance;
}
public IEnumerable<IHtmlContent> GetRegisteredHeadScripts() => DoGetRegisteredHeadScripts();
public List<IHtmlContent> DoGetRegisteredHeadScripts()
{
return _headScripts ?? EmptyList<IHtmlContent>.Instance;
}
public IEnumerable<IHtmlContent> GetRegisteredFootScripts() => DoGetRegisteredFootScripts();
public List<IHtmlContent> DoGetRegisteredFootScripts()
{
return _footScripts ?? EmptyList<IHtmlContent>.Instance;
}
public IEnumerable<IHtmlContent> GetRegisteredStyles() => DoGetRegisteredStyles();
public List<IHtmlContent> DoGetRegisteredStyles()
{
return _styles ?? EmptyList<IHtmlContent>.Instance;
}
public IEnumerable<ResourceRequiredContext> GetRequiredResources(string resourceType)
=> DoGetRequiredResources(resourceType);
private ResourceRequiredContext[] DoGetRequiredResources(string resourceType)
{
if (_builtResources.TryGetValue(resourceType, out var requiredResources) && requiredResources != null)
{
return requiredResources;
}
var allResources = new ResourceDictionary();
foreach (var settings in ResolveRequiredResources(resourceType))
{
var resource = FindResource(settings);
if (resource == null)
{
throw new InvalidOperationException($"Could not find a resource of type '{settings.Type}' named '{settings.Name}' with version '{settings.Version ?? "any"}'.");
}
ExpandDependencies(resource, settings, allResources);
}
requiredResources = new ResourceRequiredContext[allResources.Count];
int i, first = 0, byDependency = allResources.FirstCount, last = allResources.Count - allResources.LastCount;
foreach (DictionaryEntry entry in allResources)
{
var settings = (RequireSettings)entry.Value;
if (settings.Position == ResourcePosition.First)
{
i = first++;
}
else if (settings.Position == ResourcePosition.Last)
{
i = last++;
}
else
{
i = byDependency++;
}
requiredResources[i] = new ResourceRequiredContext
{
Settings = settings,
Resource = (ResourceDefinition)entry.Key,
FileVersionProvider = _fileVersionProvider
};
}
return _builtResources[resourceType] = requiredResources;
}
protected virtual void ExpandDependencies(
ResourceDefinition resource,
RequireSettings settings,
ResourceDictionary allResources)
{
if (resource == null)
{
return;
}
allResources.AddExpandingResource(resource, settings);
// Use any additional dependencies from the settings without mutating the resource that is held in a singleton collection.
List<string> dependencies = null;
if (resource.Dependencies != null)
{
dependencies = new List<string>(resource.Dependencies);
if (settings.Dependencies != null)
{
dependencies.AddRange(settings.Dependencies);
}
}
else if (settings.Dependencies != null)
{
dependencies = new List<string>(settings.Dependencies);
}
// Settings is given so they can cascade down into dependencies. For example, if Foo depends on Bar, and Foo's required
// location is Head, so too should Bar's location, similarly, if Foo is First positioned, Bar dependency should be too.
//
// forge the effective require settings for this resource
// (1) If a require exists for the resource, combine with it. Last settings in gets preference for its specified values.
// (2) If no require already exists, form a new settings object based on the given one but with its own type/name.
var dependencySettings = (((RequireSettings)allResources[resource])
?.NewAndCombine(settings)
?? new RequireSettings(_options)
{
Name = resource.Name,
Type = resource.Type,
Position = resource.Position
}
.Combine(settings))
.CombinePosition(settings)
;
if (dependencies != null)
{
// share search instance
var tempSettings = new RequireSettings();
for (var i = 0; i < dependencies.Count; i++)
{
var d = dependencies[i];
var idx = d.IndexOf(':');
var name = d;
string version = null;
if (idx != -1)
{
name = d.Substring(0, idx);
version = d[(idx + 1)..];
}
tempSettings.Type = resource.Type;
tempSettings.Name = name;
tempSettings.Version = version;
var dependency = FindResource(tempSettings);
if (dependency == null)
{
continue;
}
ExpandDependencies(dependency, dependencySettings, allResources);
}
}
settings.UpdatePositionFromDependency(dependencySettings);
allResources.AddExpandedResource(resource, dependencySettings);
}
public void RegisterLink(LinkEntry link)
{
if (_links == null)
{
_links = new List<LinkEntry>();
}
var href = link.Href;
if (href != null && href.StartsWith("~/", StringComparison.Ordinal))
{
link.Href = _options.ContentBasePath + href.Substring(1);
}
if (link.AppendVersion)
{
link.Href = _fileVersionProvider.AddFileVersionToPath(_options.ContentBasePath, link.Href);
}
_links.Add(link);
}
public void RegisterMeta(MetaEntry meta)
{
if (meta == null)
{
return;
}
if (_metas == null)
{
_metas = new Dictionary<string, MetaEntry>();
}
var index = meta.Name ?? meta.Property ?? meta.HttpEquiv ?? "charset";
_metas[index] = meta;
}
public void AppendMeta(MetaEntry meta, string contentSeparator)
{
if (meta == null)
{
return;
}
var index = meta.Name ?? meta.Property ?? meta.HttpEquiv;
if (String.IsNullOrEmpty(index))
{
return;
}
if (_metas == null)
{
_metas = new Dictionary<string, MetaEntry>();
}
if (_metas.TryGetValue(index, out var existingMeta))
{
meta = MetaEntry.Combine(existingMeta, meta, contentSeparator);
}
_metas[index] = meta;
}
public void RenderMeta(TextWriter writer)
{
var first = true;
foreach (var meta in DoGetRegisteredMetas())
{
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
meta.GetTag().WriteTo(writer, NullHtmlEncoder.Default);
}
}
public void RenderHeadLink(TextWriter writer)
{
var first = true;
var registeredLinks = DoGetRegisteredLinks();
for (var i = 0; i < registeredLinks.Count; i++)
{
var link = registeredLinks[i];
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
link.GetTag().WriteTo(writer, NullHtmlEncoder.Default);
}
}
public void RenderStylesheet(TextWriter writer)
{
var first = true;
var styleSheets = DoGetRequiredResources("stylesheet");
foreach (var context in styleSheets)
{
if (context.Settings.Location == ResourceLocation.Inline)
{
continue;
}
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
context.WriteTo(writer, _options.ContentBasePath);
}
var registeredStyles = DoGetRegisteredStyles();
for (var i = 0; i < registeredStyles.Count; i++)
{
var context = registeredStyles[i];
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
context.WriteTo(writer, NullHtmlEncoder.Default);
}
}
public void RenderHeadScript(TextWriter writer)
{
var headScripts = DoGetRequiredResources("script");
var first = true;
foreach (var context in headScripts)
{
if (context.Settings.Location != ResourceLocation.Head)
{
continue;
}
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
context.WriteTo(writer, _options.ContentBasePath);
}
var registeredHeadScripts = DoGetRegisteredHeadScripts();
for (var i = 0; i < registeredHeadScripts.Count; i++)
{
var context = registeredHeadScripts[i];
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
context.WriteTo(writer, NullHtmlEncoder.Default);
}
}
public void RenderFootScript(TextWriter writer)
{
var footScripts = DoGetRequiredResources("script");
var first = true;
foreach (var context in footScripts)
{
if (context.Settings.Location != ResourceLocation.Foot)
{
continue;
}
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
context.WriteTo(writer, _options.ContentBasePath);
}
var registeredFootScripts = DoGetRegisteredFootScripts();
for (var i = 0; i < registeredFootScripts.Count; i++)
{
var context = registeredFootScripts[i];
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
context.WriteTo(writer, NullHtmlEncoder.Default);
}
}
public void RenderLocalScript(RequireSettings settings, TextWriter writer)
{
var localScripts = DoGetRequiredResources("script");
_localScripts ??= new HashSet<string>(localScripts.Length);
var first = true;
foreach (var context in localScripts)
{
if ((context.Settings.Location == ResourceLocation.Unspecified || context.Settings.Location == ResourceLocation.Inline) &&
(_localScripts.Add(context.Settings.Name) || context.Settings.Name == settings.Name))
{
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
context.WriteTo(writer, _options.ContentBasePath);
}
}
}
public void RenderLocalStyle(RequireSettings settings, TextWriter writer)
{
var localStyles = DoGetRequiredResources("stylesheet");
_localStyles ??= new HashSet<string>(localStyles.Length);
var first = true;
foreach (var context in localStyles)
{
if (context.Settings.Location == ResourceLocation.Inline &&
(_localStyles.Add(context.Settings.Name) || context.Settings.Name == settings.Name))
{
if (!first)
{
writer.Write(System.Environment.NewLine);
}
first = false;
context.WriteTo(writer, _options.ContentBasePath);
}
}
}
private readonly struct ResourceTypeName : IEquatable<ResourceTypeName>
{
public readonly string Type;
public readonly string Name;
public ResourceTypeName(string resourceType, string resourceName)
{
Type = resourceType;
Name = resourceName;
}
public bool Equals(ResourceTypeName other)
{
return Type == other.Type && Name == other.Name;
}
public override int GetHashCode()
{
return HashCode.Combine(Type, Name);
}
public override string ToString() => "(" + Type + ", " + Name + ")";
}
private string GetResourceKey(string releasePath, string debugPath)
{
if (_options.DebugMode && !String.IsNullOrWhiteSpace(debugPath))
{
return debugPath;
}
else
{
return releasePath;
}
}
private static class EmptyList<T>
{
public static readonly List<T> Instance = new List<T>();
}
private static class EmptyValueCollection<T>
{
public static readonly Dictionary<string, T>.ValueCollection Instance = new Dictionary<string, T>.ValueCollection(new Dictionary<string, T>());
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowArgumentNullException(string paramName)
{
ThrowArgumentNullException<object>(paramName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static T ThrowArgumentNullException<T>(string paramName)
{
throw new ArgumentNullException(paramName);
}
}
}
| |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using Microsoft.Azure.Mobile.Mocks;
using Microsoft.Azure.Mobile.Server.Config;
using Microsoft.Azure.Mobile.Server.Tables.Config;
using Microsoft.Azure.Mobile.Server.TestModels;
using TestUtilities;
using Xunit;
namespace Microsoft.Azure.Mobile.Server
{
public class MappedEntityTableControllerUpdateTests : IClassFixture<MappedEntityTableControllerUpdateTests.TestContext>
{
private const string Address = "mappedtestentity";
private HttpConfiguration config;
private HttpClient testClient;
public MappedEntityTableControllerUpdateTests(MappedEntityTableControllerUpdateTests.TestContext data)
{
this.testClient = data.TestClient;
this.config = data.Config;
}
[Fact]
public async Task Post_EntityIsCreated_ReturnsCreatedWithLocationHeader()
{
TestEntity entity = CreateTestEntity();
Uri location;
// Post a new entity and verify entity returned
using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity))
{
Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
location = postResponse.Headers.Location;
Assert.NotNull(location);
TestEntity result = await postResponse.Content.ReadAsAsync<TestEntity>();
this.VerifyPostedEntity(entity, result);
}
// Query the entity back using location header value to ensure it was inserted to the db
UriBuilder queryUri = new UriBuilder(location) { };
using (HttpResponseMessage queryResponse = await this.testClient.GetAsync(queryUri.Uri))
{
Assert.Equal(HttpStatusCode.OK, queryResponse.StatusCode);
TestEntity result = await queryResponse.Content.ReadAsAsync<TestEntity>();
this.VerifyEntitiesEqual(entity, result);
Assert.NotNull(result.CreatedAt);
Assert.NotNull(result.UpdatedAt);
Assert.NotNull(result.Version);
}
}
[Fact]
public async Task Patch_EntityIsUpdated_ReturnsOk()
{
TestEntity entity = CreateTestEntity();
DateTimeOffset? createdAt;
DateTimeOffset? updatedAt;
string id;
Uri location;
// Create a new entity to update
using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity))
{
Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
location = postResponse.Headers.Location;
TestEntity result = await postResponse.Content.ReadAsAsync<TestEntity>();
this.VerifyEntitiesEqual(entity, result);
Assert.NotNull(result.CreatedAt);
Assert.NotNull(result.UpdatedAt);
Assert.NotNull(result.Version);
createdAt = result.CreatedAt;
updatedAt = result.UpdatedAt;
id = result.Id;
}
// Delay slightly to avoid resolution conflict of less than 1 ms.
await Task.Delay(50);
// Update some properties
TestEntitySimple patchEntity = new TestEntitySimple
{
Id = entity.Id,
StringValue = "Updated",
IntValue = 84
};
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = location,
Method = new HttpMethod("PATCH"),
Content = (HttpContent)new ObjectContent<TestEntitySimple>(patchEntity, this.config.Formatters.JsonFormatter)
};
using (HttpResponseMessage patchResponse = await this.testClient.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, patchResponse.StatusCode);
TestEntity result = await patchResponse.Content.ReadAsAsync<TestEntity>();
this.VerifySimpleEntitiesEqual(patchEntity, result);
Assert.Equal(createdAt, result.CreatedAt);
Assert.NotEqual(updatedAt, result.UpdatedAt);
Assert.NotNull(result.Version);
}
// Query the entity back using location header value to ensure it was updated
UriBuilder queryUri = new UriBuilder(location) { };
using (HttpResponseMessage queryResponse = await this.testClient.GetAsync(queryUri.Uri))
{
Assert.Equal(HttpStatusCode.OK, queryResponse.StatusCode);
TestEntity result = await queryResponse.Content.ReadAsAsync<TestEntity>();
this.VerifySimpleEntitiesEqual(patchEntity, result);
Assert.NotNull(result.CreatedAt);
Assert.NotNull(result.UpdatedAt);
Assert.NotNull(result.Version);
}
}
[Fact]
public async Task Patch_Returns_PreconditionFailed_WithOriginalValue_IfVersionMismatch()
{
TestEntity entity = CreateTestEntity();
string stringValue = entity.StringValue;
int intValue = entity.IntValue;
Uri location;
// create a new entity to update
using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity))
{
Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
location = postResponse.Headers.Location;
}
// Update some properties
TestEntitySimple patchEntity = new TestEntitySimple
{
Id = entity.Id,
StringValue = "Updated",
IntValue = 84
};
HttpRequestMessage patchRequest = new HttpRequestMessage
{
RequestUri = location,
Method = new HttpMethod("PATCH"),
Content = (HttpContent)new ObjectContent<TestEntitySimple>(patchEntity, this.config.Formatters.JsonFormatter)
};
patchRequest.Headers.IfMatch.Add(EntityTagHeaderValue.Parse("\"QUJDREVG\""));
using (HttpResponseMessage patchResponse = await this.testClient.SendAsync(patchRequest))
{
TestEntity conflict = await patchResponse.Content.ReadAsAsync<TestEntity>();
Assert.Equal(HttpStatusCode.PreconditionFailed, patchResponse.StatusCode);
Assert.NotNull(conflict.CreatedAt);
Assert.NotNull(conflict.UpdatedAt);
}
// Query the entity back using location header value to ensure it was *not* updated
UriBuilder queryUri = new UriBuilder(location) { };
using (HttpResponseMessage response = await this.testClient.GetAsync(queryUri.Uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestEntity result = await response.Content.ReadAsAsync<TestEntity>();
Assert.Equal(stringValue, result.StringValue);
Assert.Equal(intValue, result.IntValue);
Assert.NotNull(result.CreatedAt);
Assert.NotNull(result.UpdatedAt);
}
}
[Fact]
public async Task Replace_EntityIsUpdated_ReturnsOk()
{
TestEntity entity = CreateTestEntity();
DateTimeOffset? createdAt;
DateTimeOffset? updatedAt;
string id;
Uri location;
// Create a new entity to update
using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity))
{
Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
location = postResponse.Headers.Location;
TestEntity result = await postResponse.Content.ReadAsAsync<TestEntity>();
this.VerifyEntitiesEqual(entity, result);
Assert.NotNull(result.CreatedAt);
Assert.NotNull(result.UpdatedAt);
Assert.NotNull(result.Version);
createdAt = result.CreatedAt;
updatedAt = result.UpdatedAt;
entity.Version = result.Version;
id = result.Id;
}
// Delay slightly to avoid resolution conflict of less than 1 ms.
await Task.Delay(50);
// Update some properties
entity.StringValue = "Updated";
entity.IntValue = 84;
using (HttpResponseMessage putResponse = await this.testClient.PutAsJsonAsync(location, entity))
{
Assert.Equal(HttpStatusCode.OK, putResponse.StatusCode);
TestEntity result = await putResponse.Content.ReadAsAsync<TestEntity>();
this.VerifyEntitiesEqual(entity, result);
Assert.NotEqual(updatedAt, result.UpdatedAt);
Assert.NotNull(result.Version);
}
// Query the entity back using location header value to ensure it was updated
UriBuilder queryUri = new UriBuilder(location) { };
using (HttpResponseMessage queryResponse = await this.testClient.GetAsync(queryUri.Uri))
{
Assert.Equal(HttpStatusCode.OK, queryResponse.StatusCode);
TestEntity result = await queryResponse.Content.ReadAsAsync<TestEntity>();
this.VerifyEntitiesEqual(entity, result);
Assert.NotNull(result.CreatedAt);
Assert.NotNull(result.UpdatedAt);
Assert.NotNull(result.Version);
}
}
[Fact]
public async Task Replace_Returns_PreconditionFailed_WithOriginalValue_IfVersionMismatch()
{
TestEntity entity = CreateTestEntity();
string stringValue = entity.StringValue;
int intValue = entity.IntValue;
DateTimeOffset? createdAt;
DateTimeOffset? updatedAt;
string id;
Uri location;
// Create a new entity to update
using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity))
{
Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
location = postResponse.Headers.Location;
TestEntity result = await postResponse.Content.ReadAsAsync<TestEntity>();
this.VerifyEntitiesEqual(entity, result);
Assert.NotNull(result.CreatedAt);
Assert.NotNull(result.UpdatedAt);
Assert.NotNull(result.Version);
createdAt = result.CreatedAt;
updatedAt = result.UpdatedAt;
id = result.Id;
}
// Update some properties
entity.StringValue = "Updated";
entity.IntValue = 84;
HttpRequestMessage putRequest = new HttpRequestMessage
{
RequestUri = location,
Method = HttpMethod.Put,
Content = (HttpContent)new ObjectContent<TestEntity>(entity, this.config.Formatters.JsonFormatter)
};
putRequest.Headers.IfMatch.Add(EntityTagHeaderValue.Parse("\"QUJDREVG\""));
using (HttpResponseMessage patchResponse = await this.testClient.SendAsync(putRequest))
{
TestEntity conflict = await patchResponse.Content.ReadAsAsync<TestEntity>();
Assert.Equal(HttpStatusCode.PreconditionFailed, patchResponse.StatusCode);
Assert.NotNull(conflict.CreatedAt);
Assert.NotNull(conflict.UpdatedAt);
}
// Query the entity back using location header value to ensure it was *not* updated
UriBuilder queryUri = new UriBuilder(location) { };
using (HttpResponseMessage response = await this.testClient.GetAsync(queryUri.Uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestEntity result = await response.Content.ReadAsAsync<TestEntity>();
Assert.Equal(stringValue, result.StringValue);
Assert.Equal(intValue, result.IntValue);
Assert.NotNull(result.CreatedAt);
Assert.NotNull(result.UpdatedAt);
}
}
[Fact]
public async Task Delete_EntityIsDeleted_ReturnsNoContent()
{
TestEntity entity = CreateTestEntity();
Uri location;
// Post a new entity and verify entity returned
using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity))
{
Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
location = postResponse.Headers.Location;
}
// Delete the entity
using (HttpResponseMessage deleteResponse = await this.testClient.DeleteAsync(location))
{
Assert.Equal(HttpStatusCode.NoContent, deleteResponse.StatusCode);
}
// Try to query the entity back to ensure it was deleted
using (HttpResponseMessage queryResponse = await this.testClient.GetAsync(location))
{
Assert.Equal(HttpStatusCode.NotFound, queryResponse.StatusCode);
}
}
[Fact]
public async Task Delete_Returns_PreconditionFailed_WithOriginalValue_IfVersionMismatch()
{
TestEntity entity = CreateTestEntity();
Uri location;
// Post a new entity and verify entity returned
using (HttpResponseMessage postResponse = await this.testClient.PostAsJsonAsync(Address, entity))
{
Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
location = postResponse.Headers.Location;
}
// Try to delete the entity with wrong version
HttpRequestMessage deleteRequest = new HttpRequestMessage(HttpMethod.Delete, location);
deleteRequest.Headers.IfMatch.Add(EntityTagHeaderValue.Parse("\"QUJDREVG\""));
using (HttpResponseMessage deleteResponse = await this.testClient.SendAsync(deleteRequest))
{
TestEntity conflict = await deleteResponse.Content.ReadAsAsync<TestEntity>();
Assert.Equal(HttpStatusCode.PreconditionFailed, deleteResponse.StatusCode);
Assert.NotNull(conflict.CreatedAt);
Assert.NotNull(conflict.UpdatedAt);
}
// Query the entity back to ensure it was *not* deleted
using (HttpResponseMessage queryResponse = await this.testClient.GetAsync(location))
{
Assert.Equal(HttpStatusCode.OK, queryResponse.StatusCode);
}
}
private static TestEntity CreateTestEntity()
{
return new TestEntity()
{
Id = Guid.NewGuid().ToString(),
StringValue = "Testing",
IntValue = 84,
BooleanValue = true,
};
}
private void VerifyPostedEntity(TestEntity expected, TestEntity result)
{
// verify an ID was auto assigned
Assert.False(string.IsNullOrEmpty(result.Id));
Guid id = Guid.Parse(result.Id);
Assert.NotEqual(Guid.Empty, id);
// verify CreatedAt was set properly
Assert.True(result.CreatedAt.HasValue);
double delta = Math.Abs((result.CreatedAt.Value.ToUniversalTime() - DateTime.UtcNow).TotalSeconds);
Assert.True(delta < 100);
// verify the rest of the non-system properties
this.VerifyEntitiesEqual(expected, result);
}
private void VerifyEntitiesEqual(TestEntity expected, TestEntity result)
{
Assert.Equal(expected.StringValue, result.StringValue);
Assert.Equal(expected.IntValue, result.IntValue);
Assert.Equal(expected.BooleanValue, result.BooleanValue);
}
private void VerifySimpleEntitiesEqual(TestEntitySimple expected, TestEntity result)
{
Assert.Equal(expected.StringValue, result.StringValue);
Assert.Equal(expected.IntValue, result.IntValue);
Assert.Equal(expected.BooleanValue, result.BooleanValue);
}
public class TestContext
{
public TestContext()
{
TestHelper.ResetTestDatabase();
this.Config = new HttpConfiguration();
new MobileAppConfiguration()
.AddTables(
new MobileAppTableConfiguration()
.MapTableControllers()
.AddEntityFramework())
.ApplyTo(this.Config);
Mapper.Initialize(cfg =>
{
cfg.CreateMap<TestEntity, TestEntityModel>();
cfg.CreateMap<TestEntityModel, TestEntity>();
});
IMobileAppSettingsProvider settingsProvider = this.Config.GetMobileAppSettingsProvider();
this.Settings = settingsProvider.GetMobileAppSettings();
HttpServer server = new HttpServer(this.Config);
this.TestClient = new HttpClient(new HostMockHandler(server));
this.TestClient.BaseAddress = new Uri("http://localhost/tables/");
}
public HttpConfiguration Config { get; set; }
public MobileAppSettingsDictionary Settings { get; private set; }
public HttpClient TestClient { get; set; }
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="iCall.PerpetualHandlerBinding", Namespace="urn:iControl")]
public partial class iCallPerpetualHandler : iControlInterface {
public iCallPerpetualHandler() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_filter
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void add_filter(
string [] handlers,
string [] [] subscriptions,
string [] [] [] filters,
string [] [] [] values
) {
this.Invoke("add_filter", new object [] {
handlers,
subscriptions,
filters,
values});
}
public System.IAsyncResult Beginadd_filter(string [] handlers,string [] [] subscriptions,string [] [] [] filters,string [] [] [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_filter", new object[] {
handlers,
subscriptions,
filters,
values}, callback, asyncState);
}
public void Endadd_filter(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_subscription
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void add_subscription(
string [] handlers,
string [] [] subscriptions,
string [] [] events
) {
this.Invoke("add_subscription", new object [] {
handlers,
subscriptions,
events});
}
public System.IAsyncResult Beginadd_subscription(string [] handlers,string [] [] subscriptions,string [] [] events, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_subscription", new object[] {
handlers,
subscriptions,
events}, callback, asyncState);
}
public void Endadd_subscription(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void create(
string [] handlers,
string [] scripts
) {
this.Invoke("create", new object [] {
handlers,
scripts});
}
public System.IAsyncResult Begincreate(string [] handlers,string [] scripts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
handlers,
scripts}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_handlers
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void delete_all_handlers(
) {
this.Invoke("delete_all_handlers", new object [0]);
}
public System.IAsyncResult Begindelete_all_handlers(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_handlers", new object[0], callback, asyncState);
}
public void Enddelete_all_handlers(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_handler
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void delete_handler(
string [] handlers
) {
this.Invoke("delete_handler", new object [] {
handlers});
}
public System.IAsyncResult Begindelete_handler(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_handler", new object[] {
handlers}, callback, asyncState);
}
public void Enddelete_handler(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] handlers
) {
object [] results = this.Invoke("get_description", new object [] {
handlers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
handlers}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_filter
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] [] get_filter(
string [] handlers,
string [] [] subscriptions
) {
object [] results = this.Invoke("get_filter", new object [] {
handlers,
subscriptions});
return ((string [] [] [])(results[0]));
}
public System.IAsyncResult Beginget_filter(string [] handlers,string [] [] subscriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_filter", new object[] {
handlers,
subscriptions}, callback, asyncState);
}
public string [] [] [] Endget_filter(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_filter_match_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public iCallMatchAlgorithm [] [] [] get_filter_match_algorithm(
string [] handlers,
string [] [] subscriptions,
string [] [] [] filters
) {
object [] results = this.Invoke("get_filter_match_algorithm", new object [] {
handlers,
subscriptions,
filters});
return ((iCallMatchAlgorithm [] [] [])(results[0]));
}
public System.IAsyncResult Beginget_filter_match_algorithm(string [] handlers,string [] [] subscriptions,string [] [] [] filters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_filter_match_algorithm", new object[] {
handlers,
subscriptions,
filters}, callback, asyncState);
}
public iCallMatchAlgorithm [] [] [] Endget_filter_match_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((iCallMatchAlgorithm [] [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_filter_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] [] get_filter_value(
string [] handlers,
string [] [] subscriptions,
string [] [] [] filters
) {
object [] results = this.Invoke("get_filter_value", new object [] {
handlers,
subscriptions,
filters});
return ((string [] [] [])(results[0]));
}
public System.IAsyncResult Beginget_filter_value(string [] handlers,string [] [] subscriptions,string [] [] [] filters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_filter_value", new object[] {
handlers,
subscriptions,
filters}, callback, asyncState);
}
public string [] [] [] Endget_filter_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_handler_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public iCallPerpetualHandlerState [] get_handler_state(
string [] handlers
) {
object [] results = this.Invoke("get_handler_state", new object [] {
handlers});
return ((iCallPerpetualHandlerState [])(results[0]));
}
public System.IAsyncResult Beginget_handler_state(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_handler_state", new object[] {
handlers}, callback, asyncState);
}
public iCallPerpetualHandlerState [] Endget_handler_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((iCallPerpetualHandlerState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_script
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_script(
string [] handlers
) {
object [] results = this.Invoke("get_script", new object [] {
handlers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_script(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_script", new object[] {
handlers}, callback, asyncState);
}
public string [] Endget_script(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_subscription
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_subscription(
string [] handlers
) {
object [] results = this.Invoke("get_subscription", new object [] {
handlers});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_subscription(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_subscription", new object[] {
handlers}, callback, asyncState);
}
public string [] [] Endget_subscription(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_subscription_event
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_subscription_event(
string [] handlers,
string [] [] subscriptions
) {
object [] results = this.Invoke("get_subscription_event", new object [] {
handlers,
subscriptions});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_subscription_event(string [] handlers,string [] [] subscriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_subscription_event", new object[] {
handlers,
subscriptions}, callback, asyncState);
}
public string [] [] Endget_subscription_event(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_filters
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void remove_all_filters(
string [] handlers,
string [] [] subscriptions
) {
this.Invoke("remove_all_filters", new object [] {
handlers,
subscriptions});
}
public System.IAsyncResult Beginremove_all_filters(string [] handlers,string [] [] subscriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_filters", new object[] {
handlers,
subscriptions}, callback, asyncState);
}
public void Endremove_all_filters(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_subscriptions
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void remove_all_subscriptions(
string [] handlers
) {
this.Invoke("remove_all_subscriptions", new object [] {
handlers});
}
public System.IAsyncResult Beginremove_all_subscriptions(string [] handlers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_subscriptions", new object[] {
handlers}, callback, asyncState);
}
public void Endremove_all_subscriptions(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_filter
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void remove_filter(
string [] handlers,
string [] [] subscriptions,
string [] [] [] filters
) {
this.Invoke("remove_filter", new object [] {
handlers,
subscriptions,
filters});
}
public System.IAsyncResult Beginremove_filter(string [] handlers,string [] [] subscriptions,string [] [] [] filters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_filter", new object[] {
handlers,
subscriptions,
filters}, callback, asyncState);
}
public void Endremove_filter(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_subscription
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void remove_subscription(
string [] handlers,
string [] [] subscriptions
) {
this.Invoke("remove_subscription", new object [] {
handlers,
subscriptions});
}
public System.IAsyncResult Beginremove_subscription(string [] handlers,string [] [] subscriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_subscription", new object[] {
handlers,
subscriptions}, callback, asyncState);
}
public void Endremove_subscription(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void set_description(
string [] handlers,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
handlers,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] handlers,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
handlers,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_filter_match_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void set_filter_match_algorithm(
string [] handlers,
string [] [] subscriptions,
string [] [] [] filters,
iCallMatchAlgorithm [] [] [] algorithms
) {
this.Invoke("set_filter_match_algorithm", new object [] {
handlers,
subscriptions,
filters,
algorithms});
}
public System.IAsyncResult Beginset_filter_match_algorithm(string [] handlers,string [] [] subscriptions,string [] [] [] filters,iCallMatchAlgorithm [] [] [] algorithms, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_filter_match_algorithm", new object[] {
handlers,
subscriptions,
filters,
algorithms}, callback, asyncState);
}
public void Endset_filter_match_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_filter_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void set_filter_value(
string [] handlers,
string [] [] subscriptions,
string [] [] [] filters,
string [] [] [] values
) {
this.Invoke("set_filter_value", new object [] {
handlers,
subscriptions,
filters,
values});
}
public System.IAsyncResult Beginset_filter_value(string [] handlers,string [] [] subscriptions,string [] [] [] filters,string [] [] [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_filter_value", new object[] {
handlers,
subscriptions,
filters,
values}, callback, asyncState);
}
public void Endset_filter_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_handler_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void set_handler_state(
string [] handlers,
iCallPerpetualHandlerState [] states
) {
this.Invoke("set_handler_state", new object [] {
handlers,
states});
}
public System.IAsyncResult Beginset_handler_state(string [] handlers,iCallPerpetualHandlerState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_handler_state", new object[] {
handlers,
states}, callback, asyncState);
}
public void Endset_handler_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_script
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void set_script(
string [] handlers,
string [] scripts
) {
this.Invoke("set_script", new object [] {
handlers,
scripts});
}
public System.IAsyncResult Beginset_script(string [] handlers,string [] scripts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_script", new object[] {
handlers,
scripts}, callback, asyncState);
}
public void Endset_script(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_subscription_event
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/PerpetualHandler",
RequestNamespace="urn:iControl:iCall/PerpetualHandler", ResponseNamespace="urn:iControl:iCall/PerpetualHandler")]
public void set_subscription_event(
string [] handlers,
string [] [] subscriptions,
string [] [] events
) {
this.Invoke("set_subscription_event", new object [] {
handlers,
subscriptions,
events});
}
public System.IAsyncResult Beginset_subscription_event(string [] handlers,string [] [] subscriptions,string [] [] events, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_subscription_event", new object[] {
handlers,
subscriptions,
events}, callback, asyncState);
}
public void Endset_subscription_event(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for BackendOperations.
/// </summary>
public static partial class BackendOperationsExtensions
{
/// <summary>
/// Lists a collection of backends in the specified service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<BackendContract> ListByService(this IBackendOperations operations, string resourceGroupName, string serviceName, ODataQuery<BackendContract> odataQuery = default(ODataQuery<BackendContract>))
{
return ((IBackendOperations)operations).ListByServiceAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists a collection of backends in the specified service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<BackendContract>> ListByServiceAsync(this IBackendOperations operations, string resourceGroupName, string serviceName, ODataQuery<BackendContract> odataQuery = default(ODataQuery<BackendContract>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the details of the backend specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
public static BackendContract Get(this IBackendOperations operations, string resourceGroupName, string serviceName, string backendid)
{
return operations.GetAsync(resourceGroupName, serviceName, backendid).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the details of the backend specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BackendContract> GetAsync(this IBackendOperations operations, string resourceGroupName, string serviceName, string backendid, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, backendid, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or Updates a backend.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
public static BackendContract CreateOrUpdate(this IBackendOperations operations, string resourceGroupName, string serviceName, string backendid, BackendContract parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, backendid, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or Updates a backend.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BackendContract> CreateOrUpdateAsync(this IBackendOperations operations, string resourceGroupName, string serviceName, string backendid, BackendContract parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, backendid, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing backend.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the backend to update. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
public static void Update(this IBackendOperations operations, string resourceGroupName, string serviceName, string backendid, BackendUpdateParameters parameters, string ifMatch)
{
operations.UpdateAsync(resourceGroupName, serviceName, backendid, parameters, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing backend.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the backend to update. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this IBackendOperations operations, string resourceGroupName, string serviceName, string backendid, BackendUpdateParameters parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, backendid, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Deletes the specified backend.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the backend to delete. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
public static void Delete(this IBackendOperations operations, string resourceGroupName, string serviceName, string backendid, string ifMatch)
{
operations.DeleteAsync(resourceGroupName, serviceName, backendid, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified backend.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the backend to delete. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IBackendOperations operations, string resourceGroupName, string serviceName, string backendid, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, backendid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists a collection of backends in the specified service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<BackendContract> ListByServiceNext(this IBackendOperations operations, string nextPageLink)
{
return operations.ListByServiceNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists a collection of backends in the specified service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<BackendContract>> ListByServiceNextAsync(this IBackendOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Trady.Analysis.Indicator;
using Trady.Core;
using Trady.Importer;
using System.Globalization;
using Trady.Analysis;
using Trady.Analysis.Extension;
using Trady.Core.Infrastructure;
using Trady.Importer.Csv;
using System;
using System.Diagnostics;
namespace Trady.Test
{
[TestClass]
public class IndicatorTest
{
protected async Task<IEnumerable<IOhlcv>> ImportIOhlcvDatasAsync(string fileName = "fb.csv")
{
// Last record: 09/18/2017
var csvImporter = new CsvImporter(fileName, CultureInfo.GetCultureInfo("en-US"));
return await csvImporter.ImportAsync(string.Empty);
//var yahooImporter = new YahooFinanceImporter();
//var candles = await yahooImporter.ImportAsync("FB");
//File.WriteAllLines("fb.csv", candles.Select(c => $"{c.DateTime.ToString("d")},{c.Open},{c.High},{c.Low},{c.Close},{c.Volume}"));
//return candles;
}
protected async Task<IEnumerable<IOhlcv>> ImportCCiIOhlcvDatasAsync()
{
var csvImporter = new CsvImporter("cci_test.csv", CultureInfo.GetCultureInfo("en-US"));
return await csvImporter.ImportAsync("cci_test");
}
//protected async Task<IEnumerable<IOhlcv>> ImportSpyAsync()
//{
// var csvImporter = new CsvImporter("spx.csv", CultureInfo.GetCultureInfo("en-US"));
// return await csvImporter.ImportAsync("spx");
//}
//[TestMethod]
//public async Task TestMacdPerformanceAsync()
//{
// var sw = new Stopwatch();
// var candles = await ImportSpyAsync();
// sw.Start();
// var result = candles.Macd(12, 26, 9)[candles.Count() - 1];
// sw.Stop();
// Assert.IsTrue(false, sw.ElapsedMilliseconds.ToString());
//}
[TestMethod]
public async Task TestNviAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Nvi()[candles.Count() - 1];
Assert.IsTrue(result.Tick.Value.IsApproximatelyEquals(170.2842636m));
}
[TestMethod]
public async Task TestPviAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Pvi()[candles.Count() - 1];
Assert.IsTrue(result.Tick.Value.IsApproximatelyEquals(261.1533739m));
}
[TestMethod]
public async Task TestCciAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Cci(20)[candles.Count() - 1];
Assert.IsTrue(result.Tick.Value.IsApproximatelyEquals(8.17m));
// Fixes #103: Not getting expected CCI values
var candles2 = await ImportCCiIOhlcvDatasAsync();
var cci = candles2.Cci(14);
var result2 = cci[candles2.Count() - 1];
Assert.IsTrue(result2.Tick.Value.IsApproximatelyEquals(66.66666667m));
}
[TestMethod]
public async Task TestSmiAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Smi(15, 6, 6)[candles.Count() - 1];
Assert.IsTrue(result.Tick.Value.IsApproximatelyEquals(55.1868m));
}
[TestMethod]
public async Task TestStochRsiAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.StochRsi(14)[candles.Count() - 1];
Assert.IsTrue(0m.IsApproximatelyEquals(result.Tick.Value));
var result2 = candles.StochRsi(14).Single(v => v.DateTime == new DateTime(2017, 9, 15));
Assert.IsTrue(0.317m.IsApproximatelyEquals(result2.Tick.Value));
}
[TestMethod]
public async Task TestNmoAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Nmo(14)[candles.Count() - 1];
Assert.IsTrue(0.58m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestDownMomentumAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var results = new DownMomentum(candles, 20);
Assert.IsTrue(0m.IsApproximatelyEquals(results[candles.Count() - 1].Tick.Value));
var results2 = new DownMomentum(candles, 3);
Assert.IsTrue(3.04m.IsApproximatelyEquals(results2[candles.Count() - 1].Tick.Value));
}
[TestMethod]
public async Task TestUpMomentumAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var results = new UpMomentum(candles, 20);
Assert.IsTrue(2.6m.IsApproximatelyEquals(results[candles.Count() - 1].Tick.Value));
var results2 = new UpMomentum(candles, 3);
Assert.IsTrue(0m.IsApproximatelyEquals(results2[candles.Count() - 1].Tick.Value));
}
[TestMethod]
public async Task TestRmAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Rm(20, 4)[candles.Count() - 1];
Assert.IsTrue(1.4016m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestRmiAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Rmi(20, 4)[candles.Count() - 1];
Assert.IsTrue(58.3607m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestDymoiAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Dymoi(5, 10, 14, 30, 5)[candles.Count() - 1];
Assert.IsTrue(48.805m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestParabolicSarAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var results = candles.Sar(0.02m, 0.2m);
Assert.IsTrue(173.93m.IsApproximatelyEquals(results[candles.Count() - 1].Tick.Value));
Assert.IsTrue(169.92m.IsApproximatelyEquals(results[candles.Count() - 3].Tick.Value));
Assert.IsTrue(157.36m.IsApproximatelyEquals(results.First(r => r.DateTime == new DateTime(2017, 7, 24)).Tick.Value));
}
[TestMethod]
public async Task TestMedianAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Median(10)[candles.Count() - 1];
Assert.IsTrue(171.8649975m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestPercentileAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Percentile(30, 0.7m)[candles.Count() - 1];
Assert.IsTrue(171.3529969m.IsApproximatelyEquals(result.Tick.Value));
result = candles.Percentile(10, 0.2m)[candles.Count() - 1];
Assert.IsTrue(170.9039978m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestSmaAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Sma(30)[candles.Count() - 1];
Assert.IsTrue(170.15m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestEmaAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Ema(30)[candles.Count() - 1];
Assert.IsTrue(169.55m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestAccumDistAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result0 = candles.AccumDist()[candles.Count() - 1];
var result1 = candles.AccumDist()[candles.Count() - 2];
var result2 = candles.AccumDist()[candles.Count() - 3];
Assert.IsTrue(result0.Tick - result1.Tick < 0 && result1.Tick - result2.Tick > 0);
}
[TestMethod]
public async Task TestAroonAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Aroon(25)[candles.Count() - 1];
Assert.IsTrue(84.0m.IsApproximatelyEquals(result.Tick.Up.Value));
Assert.IsTrue(48.0m.IsApproximatelyEquals(result.Tick.Down.Value));
}
[TestMethod]
public async Task TestAroonOscAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.AroonOsc(25)[candles.Count() - 1];
Assert.IsTrue(36.0m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestAtrAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Atr(14)[candles.Count() - 1];
Assert.IsTrue(2.461m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestBbAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Bb(20, 2)[candles.Count() - 1];
Assert.IsTrue(166.15m.IsApproximatelyEquals(result.Tick.LowerBand.Value));
Assert.IsTrue(170.42m.IsApproximatelyEquals(result.Tick.MiddleBand.Value));
Assert.IsTrue(174.70m.IsApproximatelyEquals(result.Tick.UpperBand.Value));
}
[TestMethod]
public async Task TestBbWidthAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.BbWidth(20, 2)[candles.Count() - 1];
Assert.IsTrue(5.013m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestChandlrAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Chandlr(22, 3)[candles.Count() - 1];
Assert.IsTrue(166.47m.IsApproximatelyEquals(result.Tick.Long.Value));
Assert.IsTrue(172.53m.IsApproximatelyEquals(result.Tick.Short.Value));
}
[TestMethod]
public async Task TestMomentumAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Mtm()[candles.Count() - 1];
Assert.IsTrue((-1.63m).IsApproximatelyEquals(result.Tick.Value));
result = candles.Mtm(20)[candles.Count() - 1];
Assert.IsTrue(2.599991m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestRateOfChangeAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Roc()[candles.Count() - 1];
Assert.IsTrue((-0.949664419m).IsApproximatelyEquals(result.Tick.Value));
result = candles.Roc(20)[candles.Count() - 1];
Assert.IsTrue(1.55306788m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestPdiAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Pdi(14)[candles.Count() - 1];
Assert.IsTrue(16.36m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestMdiAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Mdi(14)[candles.Count() - 1];
Assert.IsTrue(19.77m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestAdxAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Adx(14)[candles.Count() - 1];
Assert.IsTrue(15.45m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestAdxrAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Adxr(14, 3)[candles.Count() - 1];
Assert.IsTrue(16.21m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestEfficiencyRatioAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Er(10)[candles.Count() - 1];
Assert.IsTrue(0.147253482m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestKamaAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Kama(10, 2, 30)[candles.Count() - 1];
Assert.IsTrue(164.88m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestEmaOscAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.EmaOsc(10, 30)[candles.Count() - 1];
Assert.IsTrue(1.83m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestHighestHighAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.HighHigh(10)[candles.Count() - 1];
Assert.IsTrue(174m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestHighestCloseAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.HighClose(10)[candles.Count() - 1];
Assert.IsTrue(173.509995m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestHistoricalHighestHighAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.HistHighHigh()[candles.Count() - 1];
Assert.IsTrue(175.490005m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestHistoricalHighestCloseAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.HistHighClose()[candles.Count() - 1];
Assert.IsTrue(173.509995m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestLowestLowAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.LowLow(10)[candles.Count() - 1];
Assert.IsTrue(169.339996m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestLowestCloseAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.LowClose(10)[candles.Count() - 1];
Assert.IsTrue(170.009995m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestHistoricalLowestLowAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.HistLowLow()[candles.Count() - 1];
Assert.IsTrue(17.549999m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestHistoricalLowestCloseAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.HistLowClose()[candles.Count() - 1];
Assert.IsTrue(17.73m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestIchimokuCloudAsync()
{
var candles = await ImportIOhlcvDatasAsync();
int middlePeriodCount = 26;
var results = candles.Ichimoku(9, middlePeriodCount, 52);
var currResult = results.ElementAt(results.Count() - middlePeriodCount - 1);
Assert.IsTrue(171.67m.IsApproximatelyEquals(currResult.Tick.ConversionLine.Value));
Assert.IsTrue(169.50m.IsApproximatelyEquals(currResult.Tick.BaseLine.Value));
var leadingResult = results.Last();
Assert.IsTrue(170.58m.IsApproximatelyEquals(leadingResult.Tick.LeadingSpanA.Value));
Assert.IsTrue(161.74m.IsApproximatelyEquals(leadingResult.Tick.LeadingSpanB.Value));
var laggingResult = results.ElementAt(results.Count() - 2 * middlePeriodCount - 1);
Assert.IsTrue(170.01m.IsApproximatelyEquals(laggingResult.Tick.LaggingSpan.Value));
}
[TestMethod]
public async Task TestMmaAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Mma(30)[candles.Count() - 1];
Assert.IsTrue(169.9556615m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestMacdAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Macd(12, 26, 9)[candles.Count() - 1];
Assert.IsTrue(1.25m.IsApproximatelyEquals(result.Tick.MacdLine.Value));
Assert.IsTrue(1.541m.IsApproximatelyEquals(result.Tick.SignalLine.Value));
Assert.IsTrue((-0.291m).IsApproximatelyEquals(result.Tick.MacdHistogram.Value));
}
[TestMethod]
public async Task TestMacdHistogramAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.MacdHist(12, 26, 9)[candles.Count() - 1];
Assert.IsTrue((-0.291m).IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestObvAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result0 = candles.Obv()[candles.Count() - 1];
var result1 = candles.Obv()[candles.Count() - 2];
var result2 = candles.Obv()[candles.Count() - 3];
Assert.IsTrue(result0.Tick - result1.Tick < 0 && result1.Tick - result2.Tick > 0);
}
[TestMethod]
public async Task TestRsvAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Rsv(14)[candles.Count() - 1];
Assert.IsTrue(55.66661111m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestRsAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Rs(14)[candles.Count() - 1];
Assert.IsTrue(1.011667673m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestRsiAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Rsi(14)[candles.Count() - 1];
Assert.IsTrue(50.29m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestSmaOscAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.SmaOsc(10, 30)[candles.Count() - 1];
Assert.IsTrue(1.76m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestSdAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Sd(10)[candles.Count() - 1];
Assert.IsTrue(1.17m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestFastStoAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.FastSto(14, 3)[candles.Count() - 1];
Assert.IsTrue(55.67m.IsApproximatelyEquals(result.Tick.K.Value));
Assert.IsTrue(65.22m.IsApproximatelyEquals(result.Tick.D.Value));
Assert.IsTrue(36.57m.IsApproximatelyEquals(result.Tick.J.Value));
}
[TestMethod]
public async Task TestSlowStoAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.SlowSto(14, 3)[candles.Count() - 1];
Assert.IsTrue(65.22m.IsApproximatelyEquals(result.Tick.K.Value));
Assert.IsTrue(74.36m.IsApproximatelyEquals(result.Tick.D.Value));
Assert.IsTrue(46.94m.IsApproximatelyEquals(result.Tick.J.Value));
}
[TestMethod]
public async Task TestFullStoAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.FullSto(14, 3, 3)[candles.Count() - 1];
Assert.IsTrue(65.22m.IsApproximatelyEquals(result.Tick.K.Value));
Assert.IsTrue(74.36m.IsApproximatelyEquals(result.Tick.D.Value));
Assert.IsTrue(46.94m.IsApproximatelyEquals(result.Tick.J.Value));
}
[TestMethod]
public async Task TestFastStoOscAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.FastStoOsc(14, 3)[candles.Count() - 1];
Assert.IsTrue((-9.55m).IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestSlowStoOscAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.SlowStoOsc(14, 3)[candles.Count() - 1];
Assert.IsTrue((-9.14m).IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestFullStoOscAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.FullStoOsc(14, 3, 3)[candles.Count() - 1];
Assert.IsTrue((-9.14m).IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestWmaAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Wma(20)[candles.Count() - 1];
Assert.IsTrue((171.2445727m).IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestHmaAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Hma(30)[candles.Count() - 1];
Assert.IsTrue((172.8926202m).IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestKcAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Kc(20, 2, 10)[candles.Count() - 1];
Assert.IsTrue(result.Tick.LowerChannel.Value.IsApproximatelyEquals(165.81m));
Assert.IsTrue(result.Tick.Middle.Value.IsApproximatelyEquals(170.65m));
Assert.IsTrue(result.Tick.UpperChannel.Value.IsApproximatelyEquals(175.50m));
}
[TestMethod]
public async Task TestVwapAsync()
{
var candles = await ImportIOhlcvDatasAsync();
var result = candles.Vwap(14)[candles.Count() - 1];
Assert.IsTrue(171.3262179m.IsApproximatelyEquals(result.Tick.Value));
}
[TestMethod]
public async Task TestVwap_IsAccurateAsync()
{
var candles = await ImportIOhlcvDatasAsync("NFLX_5m_1_27_2019.csv");
var selected = candles.Where(x => x.DateTime <= new DateTimeOffset(2019, 1, 25, 15, 15, 00, new TimeSpan(-6, 0, 0)));
var result = selected.Vwap()[selected.Count() - 1].Tick;
Assert.IsTrue(335.67m.IsApproximatelyEquals(result.Value));
}
[TestMethod]
public async Task TestVwap_CloseIsAboveVwapAsync()
{
var candles = await ImportIOhlcvDatasAsync("NFLX_5m_1_27_2019.csv");
var selected = candles.Where(x => x.DateTime <= new DateTimeOffset(2019, 1, 25, 09, 40, 00, new TimeSpan(-6, 0, 0)));
var result = selected.Vwap()[selected.Count() - 1].Tick;
var close = selected.Last().Close;
Assert.IsTrue(330.32m.IsApproximatelyEquals(result.Value));
Assert.IsTrue(close > result);
}
[TestMethod]
public async Task TestVwap_CloseIsBelowVwapAsync()
{
var candles = await ImportIOhlcvDatasAsync("NFLX_5m_1_27_2019.csv");
var selected = candles.Where(x => x.DateTime <= new DateTimeOffset(2019, 1, 25, 09, 30, 00, new TimeSpan(-6, 0, 0)));
var result = selected.Vwap()[selected.Count() - 1].Tick;
var close = selected.Last().Close;
Assert.IsTrue(329.68m.IsApproximatelyEquals(result.Value));
Assert.IsTrue(close < result);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Text
{
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
internal class DecoderNLS : Decoder, ISerializable
{
// Remember our encoding
protected EncodingNLS m_encoding;
protected bool m_mustFlush;
internal bool m_throwOnOverflow;
internal int m_bytesUsed;
internal DecoderFallback m_fallback;
internal DecoderFallbackBuffer m_fallbackBuffer;
internal DecoderNLS(EncodingNLS encoding)
{
m_encoding = encoding;
m_fallback = m_encoding.DecoderFallback;
Reset();
}
// This is used by our child deserializers
internal DecoderNLS()
{
m_encoding = null;
Reset();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
internal new DecoderFallback Fallback
{
get { return m_fallback; }
}
internal bool InternalHasFallbackBuffer
{
get
{
return m_fallbackBuffer != null;
}
}
public new DecoderFallbackBuffer FallbackBuffer
{
get
{
if (m_fallbackBuffer == null)
{
if (m_fallback != null)
m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
else
m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return m_fallbackBuffer;
}
}
public override void Reset()
{
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid null fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (byte* pBytes = &bytes[0])
return GetCharCount(pBytes + index, count, flush);
}
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember the flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
return m_encoding.GetCharCount(bytes, count, this);
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes): nameof(chars), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
// Avoid empty input fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
int charCount = chars.Length - charIndex;
if (chars.Length == 0)
chars = new char[1];
// Just call pointer version
fixed (byte* pBytes = &bytes[0])
fixed (char* pChars = &chars[0])
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, flush);
}
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember our flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding's version
return m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? nameof(bytes): nameof(chars)), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (bytes.Length == 0)
bytes = new byte[1];
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version (public overrides can't do this)
fixed (byte* pBytes = &bytes[0])
{
fixed (char* pChars = &chars[0])
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush,
out bytesUsed, out charsUsed, out completed);
}
}
}
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
[System.Security.SecurityCritical] // auto-generated
public override unsafe void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars): nameof(bytes), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
m_mustFlush = flush;
m_throwOnOverflow = false;
m_bytesUsed = 0;
// Do conversion
charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = m_bytesUsed;
// It's completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (bytesUsed == byteCount) && (!flush || !HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingies are now full, we can return
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our decoder?
internal virtual bool HasState
{
get
{
return false;
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CoreGraphicsRenderContext.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Implements a <see cref="IRenderContext"/> for MonoTouch CoreGraphics.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Xamarin.iOS
{
using System;
using System.Collections.Generic;
using System.Linq;
using CoreGraphics;
using CoreText;
using Foundation;
using UIKit;
/// <summary>
/// Implements a <see cref="IRenderContext"/> for CoreGraphics.
/// </summary>
public class CoreGraphicsRenderContext : RenderContextBase, IDisposable
{
/// <summary>
/// The images in use.
/// </summary>
private readonly HashSet<OxyImage> imagesInUse = new HashSet<OxyImage>();
/// <summary>
/// The fonts cache.
/// </summary>
private readonly Dictionary<string, CTFont> fonts = new Dictionary<string, CTFont>();
/// <summary>
/// The image cache.
/// </summary>
private readonly Dictionary<OxyImage, UIImage> imageCache = new Dictionary<OxyImage, UIImage>();
/// <summary>
/// The graphics context.
/// </summary>
private readonly CGContext gctx;
/// <summary>
/// Initializes a new instance of the <see cref="CoreGraphicsRenderContext"/> class.
/// </summary>
/// <param name="context">The context.</param>
public CoreGraphicsRenderContext(CGContext context)
{
this.gctx = context;
// Set rendering quality
this.gctx.SetAllowsFontSmoothing(true);
this.gctx.SetAllowsFontSubpixelQuantization(true);
this.gctx.SetAllowsAntialiasing(true);
this.gctx.SetShouldSmoothFonts(true);
this.gctx.SetShouldAntialias(true);
this.gctx.InterpolationQuality = CGInterpolationQuality.High;
this.gctx.SetTextDrawingMode(CGTextDrawingMode.Fill);
}
/// <summary>
/// Draws an ellipse.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The thickness.</param>
public override void DrawEllipse(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
this.SetAlias(false);
var convertedRectangle = rect.Convert();
if (fill.IsVisible())
{
this.SetFill(fill);
using (var path = new CGPath())
{
path.AddEllipseInRect(convertedRectangle);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Fill);
}
if (stroke.IsVisible() && thickness > 0)
{
this.SetStroke(stroke, thickness);
using (var path = new CGPath())
{
path.AddEllipseInRect(convertedRectangle);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws the specified portion of the specified <see cref="OxyImage" /> at the specified location and with the specified size.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="srcX">The x-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcY">The y-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcWidth">Width of the portion of the source image to draw.</param>
/// <param name="srcHeight">Height of the portion of the source image to draw.</param>
/// <param name="destX">The x-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destY">The y-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destWidth">The width of the drawn image.</param>
/// <param name="destHeight">The height of the drawn image.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolate">Interpolate if set to <c>true</c>.</param>
public override void DrawImage(OxyImage source, double srcX, double srcY, double srcWidth, double srcHeight, double destX, double destY, double destWidth, double destHeight, double opacity, bool interpolate)
{
var image = this.GetImage(source);
if (image == null)
{
return;
}
this.gctx.SaveState();
double x = destX - (srcX / srcWidth * destWidth);
double y = destY - (srcY / srcHeight * destHeight);
this.gctx.ScaleCTM(1, -1);
this.gctx.TranslateCTM((float)x, -(float)(y + destHeight));
this.gctx.SetAlpha((float)opacity);
this.gctx.InterpolationQuality = interpolate ? CGInterpolationQuality.High : CGInterpolationQuality.None;
var destRect = new CGRect(0f, 0f, (float)destWidth, (float)destHeight);
this.gctx.DrawImage(destRect, image.CGImage);
this.gctx.RestoreState();
}
/// <summary>
/// Cleans up resources not in use.
/// </summary>
/// <remarks>This method is called at the end of each rendering.</remarks>
public override void CleanUp()
{
var imagesToRelease = this.imageCache.Keys.Where(i => !this.imagesInUse.Contains(i)).ToList();
foreach (var i in imagesToRelease)
{
var image = this.GetImage(i);
image.Dispose();
this.imageCache.Remove(i);
}
this.imagesInUse.Clear();
}
/// <summary>
/// Sets the clip rectangle.
/// </summary>
/// <param name="rect">The clip rectangle.</param>
/// <returns>True if the clip rectangle was set.</returns>
public override bool SetClip(OxyRect rect)
{
this.gctx.SaveState();
this.gctx.ClipToRect(rect.Convert());
return true;
}
/// <summary>
/// Resets the clip rectangle.
/// </summary>
public override void ResetClip()
{
this.gctx.RestoreState();
}
/// <summary>
/// Draws a polyline.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public override void DrawLine(IList<ScreenPoint> points, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased)
{
if (stroke.IsVisible() && thickness > 0)
{
this.SetAlias(aliased);
this.SetStroke(stroke, thickness, dashArray, lineJoin);
using (var path = new CGPath())
{
var convertedPoints = (aliased ? points.Select(p => p.ConvertAliased()) : points.Select(p => p.Convert())).ToArray();
path.AddLines(convertedPoints);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws a polygon. The polygon can have stroke and/or fill.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">If set to <c>true</c> the shape will be aliased.</param>
public override void DrawPolygon(IList<ScreenPoint> points, OxyColor fill, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased)
{
this.SetAlias(aliased);
var convertedPoints = (aliased ? points.Select(p => p.ConvertAliased()) : points.Select(p => p.Convert())).ToArray();
if (fill.IsVisible())
{
this.SetFill(fill);
using (var path = new CGPath())
{
path.AddLines(convertedPoints);
path.CloseSubpath();
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Fill);
}
if (stroke.IsVisible() && thickness > 0)
{
this.SetStroke(stroke, thickness, dashArray, lineJoin);
using (var path = new CGPath())
{
path.AddLines(convertedPoints);
path.CloseSubpath();
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws a rectangle.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
public override void DrawRectangle(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
this.SetAlias(true);
var convertedRect = rect.ConvertAliased();
if (fill.IsVisible())
{
this.SetFill(fill);
using (var path = new CGPath())
{
path.AddRect(convertedRect);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Fill);
}
if (stroke.IsVisible() && thickness > 0)
{
this.SetStroke(stroke, thickness);
using (var path = new CGPath())
{
path.AddRect(convertedRect);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws the text.
/// </summary>
/// <param name="p">The position of the text.</param>
/// <param name="text">The text.</param>
/// <param name="fill">The fill color.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <param name="rotate">The rotation angle.</param>
/// <param name="halign">The horizontal alignment.</param>
/// <param name="valign">The vertical alignment.</param>
/// <param name="maxSize">The maximum size of the text.</param>
public override void DrawText(ScreenPoint p, string text, OxyColor fill, string fontFamily, double fontSize, double fontWeight, double rotate, HorizontalAlignment halign, VerticalAlignment valign, OxySize? maxSize)
{
if (string.IsNullOrEmpty(text))
{
return;
}
var fontName = GetActualFontName(fontFamily, fontWeight);
var font = this.GetCachedFont(fontName, fontSize);
using (var attributedString = new NSAttributedString(text, new CTStringAttributes { ForegroundColorFromContext = true, Font = font }))
{
using (var textLine = new CTLine(attributedString))
{
nfloat width;
nfloat height;
this.gctx.TextPosition = new CGPoint(0, 0);
nfloat lineHeight, delta;
this.GetFontMetrics(font, out lineHeight, out delta);
var bounds = textLine.GetImageBounds(this.gctx);
if (maxSize.HasValue || halign != HorizontalAlignment.Left || valign != VerticalAlignment.Bottom)
{
width = bounds.Left + bounds.Width;
height = lineHeight;
}
else
{
width = height = 0f;
}
if (maxSize.HasValue)
{
if (width > maxSize.Value.Width)
{
width = (float)maxSize.Value.Width;
}
if (height > maxSize.Value.Height)
{
height = (float)maxSize.Value.Height;
}
}
var dx = halign == HorizontalAlignment.Left ? 0d : (halign == HorizontalAlignment.Center ? -width * 0.5 : -width);
var dy = valign == VerticalAlignment.Bottom ? 0d : (valign == VerticalAlignment.Middle ? height * 0.5 : height);
var x0 = -bounds.Left;
var y0 = delta;
this.SetFill(fill);
this.SetAlias(false);
this.gctx.SaveState();
this.gctx.TranslateCTM((float)p.X, (float)p.Y);
if (!rotate.Equals(0))
{
this.gctx.RotateCTM((float)(rotate / 180 * Math.PI));
}
this.gctx.TranslateCTM((float)dx + x0, (float)dy + y0);
this.gctx.ScaleCTM(1f, -1f);
if (maxSize.HasValue)
{
var clipRect = new CGRect (-x0, y0, (float)Math.Ceiling (width), (float)Math.Ceiling (height));
this.gctx.ClipToRect(clipRect);
}
textLine.Draw(this.gctx);
this.gctx.RestoreState();
}
}
}
/// <summary>
/// Measures the text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>
/// The size of the text.
/// </returns>
public override OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight)
{
if (string.IsNullOrEmpty(text) || fontFamily == null)
{
return OxySize.Empty;
}
var fontName = GetActualFontName(fontFamily, fontWeight);
var font = this.GetCachedFont(fontName, (float)fontSize);
using (var attributedString = new NSAttributedString(text, new CTStringAttributes { ForegroundColorFromContext = true, Font = font }))
{
using (var textLine = new CTLine(attributedString))
{
nfloat lineHeight, delta;
this.GetFontMetrics(font, out lineHeight, out delta);
this.gctx.TextPosition = new CGPoint(0, 0);
var bounds = textLine.GetImageBounds(this.gctx);
return new OxySize(bounds.Left + bounds.Width, lineHeight);
}
}
}
/// <summary>
/// Releases all resource used by the <see cref="OxyPlot.Xamarin.iOS.CoreGraphicsRenderContext"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the
/// <see cref="OxyPlot.Xamarin.iOS.CoreGraphicsRenderContext"/>. The <see cref="Dispose"/> method leaves the
/// <see cref="OxyPlot.Xamarin.iOS.CoreGraphicsRenderContext"/> in an unusable state. After calling
/// <see cref="Dispose"/>, you must release all references to the
/// <see cref="OxyPlot.Xamarin.iOS.CoreGraphicsRenderContext"/> so the garbage collector can reclaim the memory that
/// the <see cref="OxyPlot.Xamarin.iOS.CoreGraphicsRenderContext"/> was occupying.</remarks>
public void Dispose()
{
foreach (var image in this.imageCache.Values)
{
image.Dispose();
}
foreach (var font in this.fonts.Values)
{
font.Dispose();
}
}
/// <summary>
/// Gets the actual font for iOS.
/// </summary>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>The actual font name.</returns>
private static string GetActualFontName(string fontFamily, double fontWeight)
{
string fontName;
switch (fontFamily)
{
case null:
case "Segoe UI":
fontName = "HelveticaNeue";
break;
case "Arial":
fontName = "ArialMT";
break;
case "Times":
case "Times New Roman":
fontName = "TimesNewRomanPSMT";
break;
case "Courier New":
fontName = "CourierNewPSMT";
break;
default:
fontName = fontFamily;
break;
}
if (fontWeight >= 700)
{
fontName += "-Bold";
}
return fontName;
}
/// <summary>
/// Gets font metrics for the specified font.
/// </summary>
/// <param name="font">The font.</param>
/// <param name="defaultLineHeight">Default line height.</param>
/// <param name="delta">The vertical delta.</param>
private void GetFontMetrics(CTFont font, out nfloat defaultLineHeight, out nfloat delta)
{
var ascent = font.AscentMetric;
var descent = font.DescentMetric;
var leading = font.LeadingMetric;
//// http://stackoverflow.com/questions/5511830/how-does-line-spacing-work-in-core-text-and-why-is-it-different-from-nslayoutm
leading = leading < 0 ? 0 : (float)Math.Floor(leading + 0.5f);
var lineHeight = (nfloat)Math.Floor(ascent + 0.5f) + (nfloat)Math.Floor(descent + 0.5) + leading;
var ascenderDelta = leading >= 0 ? 0 : (nfloat)Math.Floor((0.2 * lineHeight) + 0.5);
defaultLineHeight = lineHeight + ascenderDelta;
delta = ascenderDelta - descent;
}
/// <summary>
/// Gets the specified from cache.
/// </summary>
/// <returns>The font.</returns>
/// <param name="fontName">Font name.</param>
/// <param name="fontSize">Font size.</param>
private CTFont GetCachedFont(string fontName, double fontSize)
{
var key = fontName + fontSize.ToString("0.###");
CTFont font;
if (this.fonts.TryGetValue(key, out font))
{
return font;
}
return this.fonts[key] = new CTFont(fontName, (float)fontSize);
}
/// <summary>
/// Sets the alias state.
/// </summary>
/// <param name="alias">alias if set to <c>true</c>.</param>
private void SetAlias(bool alias)
{
this.gctx.SetShouldAntialias(!alias);
}
/// <summary>
/// Sets the fill color.
/// </summary>
/// <param name="c">The color.</param>
private void SetFill(OxyColor c)
{
this.gctx.SetFillColor(c.ToCGColor());
}
/// <summary>
/// Sets the stroke style.
/// </summary>
/// <param name="c">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join.</param>
private void SetStroke(OxyColor c, double thickness, double[] dashArray = null, LineJoin lineJoin = LineJoin.Miter)
{
this.gctx.SetStrokeColor(c.ToCGColor());
this.gctx.SetLineWidth((float)thickness);
this.gctx.SetLineJoin(lineJoin.Convert());
if (dashArray != null)
{
var lengths = dashArray.Select(d => (nfloat)d).ToArray();
this.gctx.SetLineDash(0f, lengths);
}
else
{
this.gctx.SetLineDash(0, null);
}
}
/// <summary>
/// Gets the image from cache or converts the specified <paramref name="source"/> <see cref="OxyImage"/>.
/// </summary>
/// <param name="source">The source.</param>
/// <returns>The image.</returns>
private UIImage GetImage(OxyImage source)
{
if (source == null)
{
return null;
}
if (!this.imagesInUse.Contains(source))
{
this.imagesInUse.Add(source);
}
UIImage src;
if (!this.imageCache.TryGetValue(source, out src))
{
using (var data = NSData.FromArray(source.GetData()))
{
src = UIImage.LoadFromData(data);
}
this.imageCache.Add(source, src);
}
return src;
}
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.Native;
namespace Microsoft.Samples.Debugging.CorDebug
{
/** A process running some managed code. */
public sealed class CorProcess : CorController, IDisposable
, IMemoryReader
{
[CLSCompliant(false)]
public static CorProcess GetCorProcess(ICorDebugProcess process)
{
Debug.Assert(process != null);
lock (m_instances)
{
if (!m_instances.Contains(process))
{
CorProcess p = new CorProcess(process);
m_instances.Add(process, p);
return p;
}
return (CorProcess)m_instances[process];
}
}
public void Dispose()
{
// Release event handlers. The event handlers are strong references and may keep
// other high-level objects (such as things in the MdbgEngine layer) alive.
m_callbacksArray = null;
if (m_callbackAttachedEvent != null)
{
m_callbackAttachedEvent.Close();
}
// Remove ourselves from instances hash.
lock (m_instances)
{
m_instances.Remove(_p());
}
}
private CorProcess(ICorDebugProcess process)
: base(process)
{
}
private static Hashtable m_instances = new Hashtable();
private ICorDebugProcess _p()
{
return (ICorDebugProcess)GetController();
}
[CLSCompliant(false)]
public ICorDebugProcess Raw
{
get
{
return _p();
}
}
#region ICorDebug Wrappers
/** The OS ID of the process. */
public int Id
{
get
{
uint id = 0;
_p().GetID(out id);
return (int)id;
}
}
/** Returns a handle to the process. */
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public IntPtr Handle
{
get
{
IntPtr h = IntPtr.Zero;
_p().GetHandle(out h);
return h;
}
}
public Version Version
{
get
{
_COR_VERSION cv;
(_p() as ICorDebugProcess2).GetVersion(out cv);
return new Version((int)cv.dwMajor, (int)cv.dwMinor, (int)cv.dwBuild, (int)cv.dwSubBuild);
}
}
/** All managed objects in the process. */
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public IEnumerable Objects
{
get
{
ICorDebugObjectEnum eobj = null;
_p().EnumerateObjects(out eobj);
return new CorObjectEnumerator(eobj);
}
}
/** Is the address inside a transition stub? */
public bool IsTransitionStub(long address)
{
int y = 0;
_p().IsTransitionStub((ulong)address, out y);
return !(y == 0);
}
/** Has the thread been suspended? */
public bool IsOSSuspended(int tid)
{
int y = 0;
_p().IsOSSuspended((uint)tid, out y);
return !(y == 0);
}
/** Gets managed thread for threadId.
* Returns NULL if tid is not a managed thread. That's very common in interop-debugging cases.
*/
public CorThread GetThread(int threadId)
{
ICorDebugThread thread = null;
try
{
_p().GetThread((uint)threadId, out thread);
}
catch (ArgumentException)
{
}
return (thread == null) ? null : (new CorThread(thread));
}
/* Get the context for the given thread. */
// See WIN32_CONTEXT structure declared in context.il
public void GetThreadContext(int threadId, IntPtr contextPtr, int context_size)
{
_p().GetThreadContext((uint)threadId, (uint)context_size, contextPtr);
return;
}
/* Get the INativeContext object for the given thread */
public INativeContext GetThreadContext(int threadId)
{
INativeContext context = ContextAllocator.GenerateContext();
using (IContextDirectAccessor w = context.OpenForDirectAccess())
{ // context buffer is now locked
// We initialize to a HUGE number so that we make sure GetThreadContext is updating the size variable. If it doesn't,
// then we will hit the assert statement below.
this.GetThreadContext(threadId, w.RawBuffer, w.Size);
}
return context;
}
/* Set the context for a given thread. */
public void SetThreadContext(int threadId, IntPtr contextPtr, int context_size)
{
_p().SetThreadContext((uint)threadId, (uint)context_size, contextPtr);
}
/* Set the INativeContext object for the given thread */
public void SetThreadContext(int threadId, INativeContext context)
{
using (IContextDirectAccessor w = context.OpenForDirectAccess())
{
// context buffer is now locked
SetThreadContext(threadId, w.RawBuffer, w.Size);
}
}
/** Read memory from the process. */
public long ReadMemory(long address, byte[] buffer)
{
Debug.Assert(buffer != null);
IntPtr read = IntPtr.Zero;
_p().ReadMemory((ulong)address, (uint)buffer.Length, buffer, out read);
return read.ToInt64();
}
void IMemoryReader.ReadMemory(IntPtr address, byte[] buffer)
{
long cbRead = ReadMemory(address.ToInt64(), buffer);
if (cbRead != buffer.LongLength)
{
throw new ReadMemoryFailureException(address, buffer.Length);
}
}
/** Write memory in the process. */
public long WriteMemory(long address, byte[] buffer)
{
IntPtr written = IntPtr.Zero;
_p().WriteMemory((ulong)address, (uint)buffer.Length, buffer, out written);
return written.ToInt64();
}
/** Clear the current unmanaged exception on the given thread. */
public void ClearCurrentException(int threadId)
{
_p().ClearCurrentException((uint)threadId);
}
/** enable/disable sending of log messages to the debugger for logging. */
public void EnableLogMessages(bool value)
{
_p().EnableLogMessages(value ? 1 : 0);
}
/** Modify the specified switches severity level */
public void ModifyLogSwitch(String name, int level)
{
_p().ModifyLogSwitch(name, level);
}
// enable or disable custom notifications of a given type
// Arguments: c - class for the type to be enabled/disabled
// value - true to enable, false to disable
public void SetEnableCustomNotification(CorClass c, bool value)
{
ICorDebugProcess3 p3 = (ICorDebugProcess3)_p();
p3.SetEnableCustomNotification(c.Raw, value ? 1 : 0);
}
/** All appdomains in the process. */
public IEnumerable AppDomains
{
get
{
ICorDebugAppDomainEnum ead = null;
_p().EnumerateAppDomains(out ead);
return new CorAppDomainEnumerator(ead);
}
}
/** Get the runtime proces object. */
public CorValue ProcessVariable
{
get
{
ICorDebugValue v = null;
_p().GetObject(out v);
return new CorValue(v);
}
}
/** These flags set things like TrackJitInfo, PreventOptimization, IgnorePDBs, and EnableEnC */
/** Any combination of bits in this DWORD flag enum is ok, but if its not a valid set, you may get an error */
public CorDebugJITCompilerFlags DesiredNGENCompilerFlags
{
get
{
uint retval = 0;
((ICorDebugProcess2)_p()).GetDesiredNGENCompilerFlags(out retval);
return (CorDebugJITCompilerFlags)retval;
}
set
{
((ICorDebugProcess2)_p()).SetDesiredNGENCompilerFlags((uint)value);
}
}
public CorReferenceValue GetReferenceValueFromGCHandle(IntPtr gchandle)
{
ICorDebugProcess2 p2 = (ICorDebugProcess2)_p();
ICorDebugReferenceValue retval;
p2.GetReferenceValueFromGCHandle(gchandle, out retval);
return new CorReferenceValue(retval);
}
/** get the thread for a cookie. */
public CorThread ThreadForFiberCookie(int cookie)
{
ICorDebugThread thread = null;
_p().ThreadForFiberCookie((uint)cookie, out thread);
return (thread == null) ? null : (new CorThread(thread));
}
/** set a BP in native code */
public byte[] SetUnmanagedBreakpoint(long address)
{
UInt32 outLen;
byte[] ret = new Byte[1];
ICorDebugProcess2 p2 = (ICorDebugProcess2)_p();
p2.SetUnmanagedBreakpoint((UInt64)address, 1, ret, out outLen);
Debug.Assert(outLen == 1);
return ret;
}
/** clear a previously set BP in native code */
public void ClearUnmanagedBreakpoint(long address)
{
ICorDebugProcess2 p2 = (ICorDebugProcess2)_p();
p2.ClearUnmanagedBreakpoint((UInt64)address);
}
public override void Stop(int timeout)
{
_p().Stop((uint)timeout);
}
public override void Continue(bool outOfBand)
{
if (!outOfBand && // OOB event can arrive anytime (we just ignore them).
(m_callbackAttachedEvent != null))
{
// first special call to "Continue" -- this fake continue will start delivering
// callbacks.
Debug.Assert(!outOfBand);
ManualResetEvent ev = m_callbackAttachedEvent;
// we set the m_callbackAttachedEvent to null first to prevent races.
m_callbackAttachedEvent = null;
ev.Set();
}
else
base.Continue(outOfBand);
}
#endregion ICorDebug Wrappers
// when process is first created wait till callbacks are enabled.
private ManualResetEvent m_callbackAttachedEvent = new ManualResetEvent(false);
private Delegate[] m_callbacksArray = new Delegate[(int)ManagedCallbackTypeCount.Last + 1];
/// <summary>
/// Expose direct dispatch logic so that other event dispatchers can
/// use CorProcess's event handlers.
/// </summary>
/// <param name="callback">callback type to dispatch</param>
/// <param name="e">event arguments used to dispatch</param>
public void DirectDispatchEvent(ManagedCallbackType callback, CorEventArgs e)
{
Debug.Assert(callback == e.CallbackType);
if (m_callbackAttachedEvent != null)
{
m_callbackAttachedEvent.Set();
}
DispatchEvent(callback, e);
}
internal void DispatchEvent(ManagedCallbackType callback, CorEventArgs e)
{
try
{
// CorProcess.Continue has an extra abstraction layer.
// - The fist call just sets m_callbackAttachedEvent
// - future calls go to ICorDebugProcess::Continue.
// This ensures that we don't dispatch any callbacks until
// after CorProcess.Continue() is called.
if (m_callbackAttachedEvent != null)
{
m_callbackAttachedEvent.WaitOne(); // waits till callbacks are enabled
}
Debug.Assert((int)callback >= 0 && (int)callback < m_callbacksArray.Length);
Delegate d = m_callbacksArray[(int)callback];
if (d != null)
{
d.DynamicInvoke(new Object[] { this, e });
}
}
catch (Exception ex)
{
CorExceptionInCallbackEventArgs e2 = new CorExceptionInCallbackEventArgs(e.Controller, ex);
Debug.Assert(false, "Exception in callback: " + ex.ToString());
try
{
// we need to dispatch the exception in callback error, but we cannot
// use DispatchEvent since throwing exception in ExceptionInCallback
// would lead to infinite recursion.
Debug.Assert(m_callbackAttachedEvent == null);
Delegate d = m_callbacksArray[(int)ManagedCallbackType.OnExceptionInCallback];
if (d != null)
d.DynamicInvoke(new Object[] { this, e2 });
}
catch (Exception ex2)
{
Debug.Assert(false, "Exception in Exception notification callback: " + ex2.ToString());
// ignore it -- there is nothing we can do.
}
e.Continue = e2.Continue;
}
}
#region Event handlers
public event BreakpointEventHandler OnBreakpoint
{
add
{
int i = (int)ManagedCallbackType.OnBreakpoint;
m_callbacksArray[i] = (BreakpointEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnBreakpoint;
m_callbacksArray[i] = (BreakpointEventHandler)m_callbacksArray[i] - value;
}
}
public event BreakpointEventHandler OnBreakpointSetError
{
add
{
int i = (int)ManagedCallbackType.OnBreakpointSetError;
m_callbacksArray[i] = (BreakpointEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnBreakpointSetError;
m_callbacksArray[i] = (BreakpointEventHandler)m_callbacksArray[i] - value;
}
}
public event StepCompleteEventHandler OnStepComplete
{
add
{
int i = (int)ManagedCallbackType.OnStepComplete;
m_callbacksArray[i] = (StepCompleteEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnStepComplete;
m_callbacksArray[i] = (StepCompleteEventHandler)m_callbacksArray[i] - value;
}
}
public event CorThreadEventHandler OnBreak
{
add
{
int i = (int)ManagedCallbackType.OnBreak;
m_callbacksArray[i] = (CorThreadEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnBreak;
m_callbacksArray[i] = (CorThreadEventHandler)m_callbacksArray[i] - value;
}
}
public event CorExceptionEventHandler OnException
{
add
{
int i = (int)ManagedCallbackType.OnException;
m_callbacksArray[i] = (CorExceptionEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnException;
m_callbacksArray[i] = (CorExceptionEventHandler)m_callbacksArray[i] - value;
}
}
public event EvalEventHandler OnEvalComplete
{
add
{
int i = (int)ManagedCallbackType.OnEvalComplete;
m_callbacksArray[i] = (EvalEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnEvalComplete;
m_callbacksArray[i] = (EvalEventHandler)m_callbacksArray[i] - value;
}
}
public event EvalEventHandler OnEvalException
{
add
{
int i = (int)ManagedCallbackType.OnEvalException;
m_callbacksArray[i] = (EvalEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnEvalException;
m_callbacksArray[i] = (EvalEventHandler)m_callbacksArray[i] - value;
}
}
public event CorProcessEventHandler OnCreateProcess
{
add
{
int i = (int)ManagedCallbackType.OnCreateProcess;
m_callbacksArray[i] = (CorProcessEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnCreateProcess;
m_callbacksArray[i] = (CorProcessEventHandler)m_callbacksArray[i] - value;
}
}
public event CorProcessEventHandler OnProcessExit
{
add
{
int i = (int)ManagedCallbackType.OnProcessExit;
m_callbacksArray[i] = (CorProcessEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnProcessExit;
m_callbacksArray[i] = (CorProcessEventHandler)m_callbacksArray[i] - value;
}
}
public event CorThreadEventHandler OnCreateThread
{
add
{
int i = (int)ManagedCallbackType.OnCreateThread;
m_callbacksArray[i] = (CorThreadEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnCreateThread;
m_callbacksArray[i] = (CorThreadEventHandler)m_callbacksArray[i] - value;
}
}
public event CorThreadEventHandler OnThreadExit
{
add
{
int i = (int)ManagedCallbackType.OnThreadExit;
m_callbacksArray[i] = (CorThreadEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnThreadExit;
m_callbacksArray[i] = (CorThreadEventHandler)m_callbacksArray[i] - value;
}
}
public event CorModuleEventHandler OnModuleLoad
{
add
{
int i = (int)ManagedCallbackType.OnModuleLoad;
m_callbacksArray[i] = (CorModuleEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnModuleLoad;
m_callbacksArray[i] = (CorModuleEventHandler)m_callbacksArray[i] - value;
}
}
public event CorModuleEventHandler OnModuleUnload
{
add
{
int i = (int)ManagedCallbackType.OnModuleUnload;
m_callbacksArray[i] = (CorModuleEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnModuleUnload;
m_callbacksArray[i] = (CorModuleEventHandler)m_callbacksArray[i] - value;
}
}
public event CorClassEventHandler OnClassLoad
{
add
{
int i = (int)ManagedCallbackType.OnClassLoad;
m_callbacksArray[i] = (CorClassEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnClassLoad;
m_callbacksArray[i] = (CorClassEventHandler)m_callbacksArray[i] - value;
}
}
public event CorClassEventHandler OnClassUnload
{
add
{
int i = (int)ManagedCallbackType.OnClassUnload;
m_callbacksArray[i] = (CorClassEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnClassUnload;
m_callbacksArray[i] = (CorClassEventHandler)m_callbacksArray[i] - value;
}
}
public event DebuggerErrorEventHandler OnDebuggerError
{
add
{
int i = (int)ManagedCallbackType.OnDebuggerError;
m_callbacksArray[i] = (DebuggerErrorEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnDebuggerError;
m_callbacksArray[i] = (DebuggerErrorEventHandler)m_callbacksArray[i] - value;
}
}
public event MDANotificationEventHandler OnMDANotification
{
add
{
int i = (int)ManagedCallbackType.OnMDANotification;
m_callbacksArray[i] = (MDANotificationEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnMDANotification;
m_callbacksArray[i] = (MDANotificationEventHandler)m_callbacksArray[i] - value;
}
}
public event LogMessageEventHandler OnLogMessage
{
add
{
int i = (int)ManagedCallbackType.OnLogMessage;
m_callbacksArray[i] = (LogMessageEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnLogMessage;
m_callbacksArray[i] = (LogMessageEventHandler)m_callbacksArray[i] - value;
}
}
public event LogSwitchEventHandler OnLogSwitch
{
add
{
int i = (int)ManagedCallbackType.OnLogSwitch;
m_callbacksArray[i] = (LogSwitchEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnLogSwitch;
m_callbacksArray[i] = (LogSwitchEventHandler)m_callbacksArray[i] - value;
}
}
// add/remove handlers for CustomNotification events
public event CustomNotificationEventHandler OnCustomNotification
{
add
{
int i = (int)ManagedCallbackType.OnCustomNotification;
m_callbacksArray[i] = (CustomNotificationEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnCustomNotification;
m_callbacksArray[i] = (CustomNotificationEventHandler)m_callbacksArray[i] - value;
}
}
public event CorAppDomainEventHandler OnCreateAppDomain
{
add
{
int i = (int)ManagedCallbackType.OnCreateAppDomain;
m_callbacksArray[i] = (CorAppDomainEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnCreateAppDomain;
m_callbacksArray[i] = (CorAppDomainEventHandler)m_callbacksArray[i] - value;
}
}
public event CorAppDomainEventHandler OnAppDomainExit
{
add
{
int i = (int)ManagedCallbackType.OnAppDomainExit;
m_callbacksArray[i] = (CorAppDomainEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnAppDomainExit;
m_callbacksArray[i] = (CorAppDomainEventHandler)m_callbacksArray[i] - value;
}
}
public event CorAssemblyEventHandler OnAssemblyLoad
{
add
{
int i = (int)ManagedCallbackType.OnAssemblyLoad;
m_callbacksArray[i] = (CorAssemblyEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnAssemblyLoad;
m_callbacksArray[i] = (CorAssemblyEventHandler)m_callbacksArray[i] - value;
}
}
public event CorAssemblyEventHandler OnAssemblyUnload
{
add
{
int i = (int)ManagedCallbackType.OnAssemblyUnload;
m_callbacksArray[i] = (CorAssemblyEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnAssemblyUnload;
m_callbacksArray[i] = (CorAssemblyEventHandler)m_callbacksArray[i] - value;
}
}
public event CorProcessEventHandler OnControlCTrap
{
add
{
int i = (int)ManagedCallbackType.OnControlCTrap;
m_callbacksArray[i] = (CorProcessEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnControlCTrap;
m_callbacksArray[i] = (CorProcessEventHandler)m_callbacksArray[i] - value;
}
}
public event CorThreadEventHandler OnNameChange
{
add
{
int i = (int)ManagedCallbackType.OnNameChange;
m_callbacksArray[i] = (CorThreadEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnNameChange;
m_callbacksArray[i] = (CorThreadEventHandler)m_callbacksArray[i] - value;
}
}
public event UpdateModuleSymbolsEventHandler OnUpdateModuleSymbols
{
add
{
int i = (int)ManagedCallbackType.OnUpdateModuleSymbols;
m_callbacksArray[i] = (UpdateModuleSymbolsEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnUpdateModuleSymbols;
m_callbacksArray[i] = (UpdateModuleSymbolsEventHandler)m_callbacksArray[i] - value;
}
}
public event CorFunctionRemapOpportunityEventHandler OnFunctionRemapOpportunity
{
add
{
int i = (int)ManagedCallbackType.OnFunctionRemapOpportunity;
m_callbacksArray[i] = (CorFunctionRemapOpportunityEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnFunctionRemapOpportunity;
m_callbacksArray[i] = (CorFunctionRemapOpportunityEventHandler)m_callbacksArray[i] - value;
}
}
public event CorFunctionRemapCompleteEventHandler OnFunctionRemapComplete
{
add
{
int i = (int)ManagedCallbackType.OnFunctionRemapComplete;
m_callbacksArray[i] = (CorFunctionRemapCompleteEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnFunctionRemapComplete;
m_callbacksArray[i] = (CorFunctionRemapCompleteEventHandler)m_callbacksArray[i] - value;
}
}
public event CorException2EventHandler OnException2
{
add
{
int i = (int)ManagedCallbackType.OnException2;
m_callbacksArray[i] = (CorException2EventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnException2;
m_callbacksArray[i] = (CorException2EventHandler)m_callbacksArray[i] - value;
}
}
public event CorExceptionUnwind2EventHandler OnExceptionUnwind2
{
add
{
int i = (int)ManagedCallbackType.OnExceptionUnwind2;
m_callbacksArray[i] = (CorExceptionUnwind2EventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnExceptionUnwind2;
m_callbacksArray[i] = (CorExceptionUnwind2EventHandler)m_callbacksArray[i] - value;
}
}
public event CorExceptionInCallbackEventHandler OnExceptionInCallback
{
add
{
int i = (int)ManagedCallbackType.OnExceptionInCallback;
m_callbacksArray[i] = (CorExceptionInCallbackEventHandler)m_callbacksArray[i] + value;
}
remove
{
int i = (int)ManagedCallbackType.OnExceptionInCallback;
m_callbacksArray[i] = (CorExceptionInCallbackEventHandler)m_callbacksArray[i] - value;
}
}
#endregion Event handlers
} /* class Process */
} /* namespace */
| |
//
// System.Collections.Stack
//
// Author:
using System.Runtime.InteropServices;
namespace Morph.Collections
{
public class Stack : ICollection, IEnumerable, ICloneable
{
// properties
private object[] contents;
private int current = -1;
private int count;
private int capacity;
private int modCount;
const int default_capacity = 16;
private void Resize(int ncapacity)
{
ncapacity = Math.Max(ncapacity, 16);
object[] ncontents = new object[ncapacity];
System.Array.Copy(contents, ncontents, count);
capacity = ncapacity;
contents = ncontents;
}
public Stack()
{
contents = new object[default_capacity];
capacity = default_capacity;
}
public Stack(System.Collections.ICollection col) : this(col == null ? 16 : col.Count)
{
if (col == null)
throw new System.ArgumentNullException("col");
// We have to do this because msft seems to call the
// enumerator rather than CopyTo. This affects classes
// like bitarray.
foreach (object o in col)
Push(o);
}
public Stack(int initialCapacity)
{
if (initialCapacity < 0)
throw new System.ArgumentOutOfRangeException("initialCapacity");
capacity = initialCapacity;
contents = new object[capacity];
}
private class SyncStack : Stack
{
Stack stack;
internal SyncStack(Stack s)
{
stack = s;
}
public override int Count
{
get
{
lock (stack)
{
return stack.Count;
}
}
}
/*
public override bool IsReadOnly {
get {
lock (stack) {
return stack.IsReadOnly;
}
}
}
*/
public override bool IsSynchronized
{
get { return true; }
}
public override object SyncRoot
{
get { return stack.SyncRoot; }
}
public override void Clear()
{
lock (stack) { stack.Clear(); }
}
public override object Clone()
{
lock (stack)
{
return Stack.Synchronized((Stack)stack.Clone());
}
}
public override bool Contains(object obj)
{
lock (stack) { return stack.Contains(obj); }
}
public override void CopyTo(System.Array array, int index)
{
lock (stack) { stack.CopyTo(array, index); }
}
public override IEnumerator GetEnumerator()
{
lock (stack)
{
return new Enumerator(stack);
}
}
public override object Peek()
{
lock (stack) { return stack.Peek(); }
}
public override object Pop()
{
lock (stack) { return stack.Pop(); }
}
public override void Push(object obj)
{
lock (stack) { stack.Push(obj); }
}
public override object[] ToArray()
{
lock (stack) { return stack.ToArray(); }
}
}
public static Stack Synchronized(Stack stack)
{
if (stack == null)
throw new System.ArgumentNullException("stack");
return new SyncStack(stack);
}
public virtual int Count
{
get { return count; }
}
/*
public virtual bool IsReadOnly {
get { return false; }
}
*/
public virtual bool IsSynchronized
{
get { return false; }
}
public virtual object SyncRoot
{
get { return this; }
}
public virtual void Clear()
{
modCount++;
for (int i = 0; i < count; i++)
{
contents[i] = null;
}
count = 0;
current = -1;
}
public virtual object Clone()
{
Stack stack = new Stack(contents);
stack.current = current;
stack.count = count;
return stack;
}
public virtual bool Contains(object obj)
{
if (count == 0)
return false;
if (obj == null)
{
for (int i = 0; i < count; i++)
{
if (contents[i] == null)
return true;
}
}
else
{
for (int i = 0; i < count; i++)
{
if (obj.Equals(contents[i]))
return true;
}
}
return false;
}
public virtual void CopyTo(System.Array array, int index)
{
if (array == null)
{
throw new System.ArgumentNullException("array");
}
if (index < 0)
{
throw new System.ArgumentOutOfRangeException("index");
}
if (array.Rank > 1 ||
array.Length > 0 && index >= array.Length ||
count > array.Length - index)
{
throw new System.ArgumentException();
}
for (int i = current; i != -1; i--)
{
array.SetValue(contents[i],
count - (i + 1) + index);
}
}
private class Enumerator : IEnumerator, ICloneable
{
const int EOF = -1;
const int BOF = -2;
Stack stack;
private int modCount;
private int current;
internal Enumerator(Stack s)
{
stack = s;
modCount = s.modCount;
current = BOF;
}
public object Clone()
{
return MemberwiseClone();
}
public virtual object Current
{
get
{
if (modCount != stack.modCount
|| current == BOF
|| current == EOF
|| current > stack.count)
{
throw new System.InvalidOperationException();
}
return stack.contents[current];
}
}
public virtual bool MoveNext()
{
if (modCount != stack.modCount)
{
throw new System.InvalidOperationException();
}
switch (current)
{
case BOF:
current = stack.current;
return current != -1;
case EOF:
return false;
default:
current--;
return current != -1;
}
}
public virtual void Reset()
{
if (modCount != stack.modCount)
{
throw new System.InvalidOperationException();
}
current = BOF;
}
}
public virtual IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
public virtual object Peek()
{
if (current == -1)
{
throw new System.InvalidOperationException();
}
else
{
return contents[current];
}
}
public virtual object Pop()
{
if (current == -1)
{
throw new System.InvalidOperationException();
}
else
{
modCount++;
object ret = contents[current];
contents[current] = null;
count--;
current--;
// if we're down to capacity/4, go back to a
// lower array size. this should keep us from
// sucking down huge amounts of memory when
// putting large numbers of items in the Stack.
// if we're lower than 16, don't bother, since
// it will be more trouble than it's worth.
if (count <= (capacity / 4) && count > 16)
{
Resize(capacity / 2);
}
return ret;
}
}
public virtual void Push(object obj)
{
modCount++;
if (capacity == count)
{
Resize(capacity * 2);
}
count++;
current++;
contents[current] = obj;
}
public virtual object[] ToArray()
{
object[] ret = new object[count];
System.Array.Copy(contents, ret, count);
// ret needs to be in LIFO order
System.Array.Reverse(ret);
return ret;
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using Microsoft.Win32;
using Xunit;
public class RegistryTests : NLogTestBase, IDisposable
{
private const string TestKey = @"Software\NLogTest";
public RegistryTests()
{
var key = Registry.CurrentUser.CreateSubKey(TestKey);
key.SetValue("Foo", "FooValue");
key.SetValue(null, "UnnamedValue");
#if !NET3_5
//different keys because in 32bit the 64bits uses the 32
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).CreateSubKey("Software\\NLogTest").SetValue("view32", "reg32");
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).CreateSubKey("Software\\NLogTest").SetValue("view64", "reg64");
#endif
}
public void Dispose()
{
#if !NET3_5
//different keys because in 32bit the 64bits uses the 32
try
{
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).DeleteSubKey("Software\\NLogTest");
}
catch (Exception)
{
}
try
{
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).DeleteSubKey("Software\\NLogTest");
}
catch (Exception)
{
}
#endif
try
{
Registry.CurrentUser.DeleteSubKey(TestKey);
}
catch (Exception)
{
}
}
[Fact]
public void RegistryNamedValueTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=Foo}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "FooValue");
}
#if !NET3_5
[Fact]
public void RegistryNamedValueTest_hive32()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view32:view=Registry32}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "reg32");
}
[Fact]
public void RegistryNamedValueTest_hive64()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view64:view=Registry64}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "reg64");
}
#endif
[Fact]
public void RegistryNamedValueTest_forward_slash()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest:value=Foo}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "FooValue");
}
[Fact]
public void RegistryUnnamedValueTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "UnnamedValue");
}
[Fact]
public void RegistryUnnamedValueTest_forward_slash()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "UnnamedValue");
}
[Fact]
public void RegistryKeyNotFoundTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NoSuchKey:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryKeyNotFoundTest_forward_slash()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NoSuchKey:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryValueNotFoundTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=NoSuchValue:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryDefaultValueTest()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=logdefaultvalue}",
"logdefaultvalue");
}
[Fact]
public void RegistryDefaultValueTest_with_colon()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\:temp}",
"C:temp");
}
[Fact]
public void RegistryDefaultValueTest_with_slash()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C/temp}",
"C/temp");
}
[Fact]
public void RegistryDefaultValueTest_with_foward_slash()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\\\temp}",
"C\\temp");
}
[Fact]
public void RegistryDefaultValueTest_with_foward_slash2()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\temp:requireEscapingSlashesInDefaultValue=false}",
"C\\temp");
}
[Fact]
public void Registry_nosubky()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:key=HKEY_CURRENT_CONFIG}", "");
}
[Fact]
public void RegistryDefaultValueNull()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT}", "");
}
[Fact]
public void RegistryTestWrongKey_no_ex()
{
LogManager.ThrowExceptions = false;
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", "");
}
[Fact(Skip = "SimpleLayout.GetFormattedMessage catches exception. Will be fixed in the future")]
public void RegistryTestWrongKey_ex()
{
LogManager.ThrowExceptions = true;
Assert.Throws<ArgumentException>(
() => { AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", ""); });
}
}
}
| |
// 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.Text;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.MethodInfos;
using System.Reflection.Runtime.ParameterInfos;
using System.Reflection.Runtime.CustomAttributes;
using Internal.Reflection.Core;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Tracing;
namespace System.Reflection.Runtime.PropertyInfos
{
//
// The runtime's implementation of PropertyInfo's
//
[DebuggerDisplay("{_debugName}")]
internal abstract partial class RuntimePropertyInfo : PropertyInfo, ITraceableTypeMember
{
//
// propertyHandle - the "tkPropertyDef" that identifies the property.
// definingType - the "tkTypeDef" that defined the field (this is where you get the metadata reader that created propertyHandle.)
// contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you
// get your raw information from "definingType", you report "contextType" as your DeclaringType property.
//
// For example:
//
// typeof(Foo<>).GetTypeInfo().DeclaredMembers
//
// The definingType and contextType are both Foo<>
//
// typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers
//
// The definingType is "Foo<,>"
// The contextType is "Foo<int,String>"
//
// We don't report any DeclaredMembers for arrays or generic parameters so those don't apply.
//
protected RuntimePropertyInfo(RuntimeTypeInfo contextTypeInfo, RuntimeTypeInfo reflectedType)
{
ContextTypeInfo = contextTypeInfo;
_reflectedType = reflectedType;
}
public sealed override bool CanRead
{
get
{
return Getter != null;
}
}
public sealed override bool CanWrite
{
get
{
return Setter != null;
}
}
public sealed override Type DeclaringType
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.PropertyInfo_DeclaringType(this);
#endif
return ContextTypeInfo;
}
}
public sealed override ParameterInfo[] GetIndexParameters()
{
ParameterInfo[] indexParameters = _lazyIndexParameters;
if (indexParameters == null)
{
bool useGetter = CanRead;
RuntimeMethodInfo accessor = (useGetter ? Getter : Setter);
RuntimeParameterInfo[] runtimeMethodParameterInfos = accessor.RuntimeParameters;
int count = runtimeMethodParameterInfos.Length;
if (!useGetter)
count--; // If we're taking the parameters off the setter, subtract one for the "value" parameter.
if (count == 0)
{
_lazyIndexParameters = indexParameters = Array.Empty<ParameterInfo>();
}
else
{
indexParameters = new ParameterInfo[count];
for (int i = 0; i < count; i++)
{
indexParameters[i] = RuntimePropertyIndexParameterInfo.GetRuntimePropertyIndexParameterInfo(this, runtimeMethodParameterInfos[i]);
}
_lazyIndexParameters = indexParameters;
}
}
int numParameters = indexParameters.Length;
if (numParameters == 0)
return indexParameters;
ParameterInfo[] result = new ParameterInfo[numParameters];
for (int i = 0; i < numParameters; i++)
{
result[i] = indexParameters[i];
}
return result;
}
public sealed override MethodInfo GetMethod
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.PropertyInfo_GetMethod(this);
#endif
return Getter;
}
}
public sealed override Type[] GetOptionalCustomModifiers() => PropertyTypeHandle.GetCustomModifiers(ContextTypeInfo.TypeContext, optional: true);
public sealed override Type[] GetRequiredCustomModifiers() => PropertyTypeHandle.GetCustomModifiers(ContextTypeInfo.TypeContext, optional: false);
public sealed override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.PropertyInfo_GetValue(this, obj, index);
#endif
if (_lazyGetterInvoker == null)
{
if (!CanRead)
throw new ArgumentException();
_lazyGetterInvoker = Getter.GetUncachedMethodInvoker(Array.Empty<RuntimeTypeInfo>(), this);
}
if (index == null)
index = Array.Empty<Object>();
return _lazyGetterInvoker.Invoke(obj, index, binder, invokeAttr, culture);
}
public abstract override bool HasSameMetadataDefinitionAs(MemberInfo other);
public sealed override Module Module
{
get
{
return DefiningTypeInfo.Module;
}
}
public sealed override String Name
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.PropertyInfo_Name(this);
#endif
return MetadataName;
}
}
public sealed override Type PropertyType
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.PropertyInfo_PropertyType(this);
#endif
TypeContext typeContext = ContextTypeInfo.TypeContext;
return PropertyTypeHandle.Resolve(typeContext);
}
}
public sealed override Type ReflectedType
{
get
{
return _reflectedType;
}
}
public sealed override MethodInfo SetMethod
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.PropertyInfo_SetMethod(this);
#endif
return Setter;
}
}
public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.PropertyInfo_SetValue(this, obj, value, index);
#endif
if (_lazySetterInvoker == null)
{
if (!CanWrite)
throw new ArgumentException();
_lazySetterInvoker = Setter.GetUncachedMethodInvoker(Array.Empty<RuntimeTypeInfo>(), this);
}
Object[] arguments;
if (index == null)
{
arguments = new Object[] { value };
}
else
{
arguments = new Object[index.Length + 1];
for (int i = 0; i < index.Length; i++)
{
arguments[i] = index[i];
}
arguments[index.Length] = value;
}
_lazySetterInvoker.Invoke(obj, arguments, binder, invokeAttr, culture);
}
public sealed override String ToString()
{
StringBuilder sb = new StringBuilder(30);
TypeContext typeContext = ContextTypeInfo.TypeContext;
sb.Append(PropertyTypeHandle.FormatTypeName(typeContext));
sb.Append(' ');
sb.Append(this.Name);
ParameterInfo[] indexParameters = this.GetIndexParameters();
if (indexParameters.Length != 0)
{
RuntimeParameterInfo[] indexRuntimeParameters = new RuntimeParameterInfo[indexParameters.Length];
for (int i = 0; i < indexParameters.Length; i++)
indexRuntimeParameters[i] = (RuntimeParameterInfo)(indexParameters[i]);
sb.Append(" [");
sb.Append(RuntimeMethodHelpers.ComputeParametersString(indexRuntimeParameters));
sb.Append(']');
}
return sb.ToString();
}
String ITraceableTypeMember.MemberName
{
get
{
return MetadataName;
}
}
Type ITraceableTypeMember.ContainingType
{
get
{
return ContextTypeInfo;
}
}
private RuntimeNamedMethodInfo Getter
{
get
{
RuntimeNamedMethodInfo getter = _lazyGetter;
if (getter == null)
{
getter = GetPropertyMethod(PropertyMethodSemantics.Getter);
if (getter == null)
getter = RuntimeDummyMethodInfo.Instance;
_lazyGetter = getter;
}
return object.ReferenceEquals(getter, RuntimeDummyMethodInfo.Instance) ? null : getter;
}
}
private RuntimeNamedMethodInfo Setter
{
get
{
RuntimeNamedMethodInfo setter = _lazySetter;
if (setter == null)
{
setter = GetPropertyMethod(PropertyMethodSemantics.Setter);
if (setter == null)
setter = RuntimeDummyMethodInfo.Instance;
_lazySetter = setter;
}
return object.ReferenceEquals(setter, RuntimeDummyMethodInfo.Instance) ? null : setter;
}
}
protected RuntimePropertyInfo WithDebugName()
{
bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled;
#if DEBUG
populateDebugNames = true;
#endif
if (!populateDebugNames)
return this;
if (_debugName == null)
{
_debugName = "Constructing..."; // Protect against any inadvertent reentrancy.
_debugName = MetadataName;
}
return this;
}
// Types that derive from RuntimePropertyInfo must implement the following public surface area members
public abstract override PropertyAttributes Attributes { get; }
public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; }
public abstract override bool Equals(Object obj);
public abstract override int GetHashCode();
public abstract override int MetadataToken { get; }
public sealed override object GetConstantValue() => GetConstantValue(raw: false);
public sealed override object GetRawConstantValue() => GetConstantValue(raw: true);
protected abstract bool GetDefaultValueIfAny(bool raw, out object defaultValue);
/// <summary>
/// Return a qualified handle that can be used to get the type of the property.
/// </summary>
protected abstract QSignatureTypeHandle PropertyTypeHandle { get; }
protected enum PropertyMethodSemantics
{
Getter,
Setter,
}
/// <summary>
/// Override to return the Method that corresponds to the specified semantic.
/// Return null if a method of the appropriate semantic does not exist
/// </summary>
protected abstract RuntimeNamedMethodInfo GetPropertyMethod(PropertyMethodSemantics whichMethod);
/// <summary>
/// Override to provide the metadata based name of a property. (Different from the Name
/// property in that it does not go into the reflection trace logic.)
/// </summary>
protected abstract string MetadataName { get; }
/// <summary>
/// Return the DefiningTypeInfo as a RuntimeTypeInfo (instead of as a format specific type info)
/// </summary>
protected abstract RuntimeTypeInfo DefiningTypeInfo { get; }
protected readonly RuntimeTypeInfo ContextTypeInfo;
protected readonly RuntimeTypeInfo _reflectedType;
private object GetConstantValue(bool raw)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.PropertyInfo_GetConstantValue(this);
#endif
object defaultValue;
if (!GetDefaultValueIfAny(raw, out defaultValue))
{
throw new InvalidOperationException(SR.Arg_EnumLitValueNotFound);
}
return defaultValue;
}
private volatile MethodInvoker _lazyGetterInvoker = null;
private volatile MethodInvoker _lazySetterInvoker = null;
private volatile RuntimeNamedMethodInfo _lazyGetter;
private volatile RuntimeNamedMethodInfo _lazySetter;
private volatile ParameterInfo[] _lazyIndexParameters;
private String _debugName;
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2021 Tim Stair
//
// 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.ComponentModel;
using System.IO;
using System.Windows.Forms;
namespace Support.UI
{
/// <summary>
/// Handles Form "dirty/clean" states in relation to file loading / saving. Acts as
/// an abstract class, but is not. (forms & abstraction break the IDE in MSVS2003)
/// Be sure to override SaveFormData and OpenFormData
/// </summary>
//public abstract class AbstractDirtyForm
public class AbstractDirtyForm : Form
{
private string m_sCurrentDirectory = string.Empty;
protected string m_sBaseTitle = string.Empty;
protected string m_sLoadedFile = string.Empty;
protected string m_sFileOpenFilter = string.Empty;
public string LoadedFile => m_sLoadedFile;
public bool Dirty { get; private set; }
/// <summary>
/// This method should have an override that performs the save of the data to the file.
/// </summary>
/// <param name="sFileName">The file to save the data to</param>
/// <returns>true on success, false otherwise</returns>
protected virtual bool SaveFormData(string sFileName)
{
MessageBox.Show(this, "DEV Error: Please override AbstractDirtyForm.SaveFormData");
return false;
}
/// <summary>
/// This method should have an override that performs the load of the data from the file.
/// </summary>
/// <param name="sFileName">The file to load the data from</param>
/// <returns>true on success, false otherwise</returns>
protected virtual bool OpenFormData(string sFileName)
{
MessageBox.Show(this, "DEV Error: Please override AbstractDirtyForm.OpenFormData");
return false;
}
/// <summary>
/// Gets the current directory associated with the form
/// </summary>
/// <returns>Current directory for the form, defaults to the current environment</returns>
private string GetDialogDirectory()
{
if (Directory.Exists(m_sCurrentDirectory))
return m_sCurrentDirectory;
return Environment.CurrentDirectory;
}
/// <summary>
/// Marks this form as dirty (needing save)
/// </summary>
public void MarkDirty()
{
if(!Dirty)
{
if(!Text.EndsWith("*"))
Text += " *";
Dirty = true;
}
}
/// <summary>
/// Marks this form as clean (save not needed)
/// </summary>
public void MarkClean()
{
if (Dirty)
{
Text = Text.Replace("*", "").Trim();
Dirty = false;
}
}
/// <summary>
/// Initializes a simple new file
/// </summary>
protected void InitNew()
{
m_sLoadedFile = string.Empty;
Text = m_sBaseTitle;
MarkClean();
}
protected bool IsOpenCanceledByDirty()
{
// need to check if there is something to save
var cancelEventArgs = new CancelEventArgs();
SaveOnEvent(cancelEventArgs, true);
return cancelEventArgs.Cancel;
}
/// <summary>
/// Initializes the Open process via the OpenFileDialog
/// </summary>
public void InitOpen()
{
if(IsOpenCanceledByDirty()) return;
var ofn = new OpenFileDialog
{
InitialDirectory = GetDialogDirectory(),
Filter = 0 == m_sFileOpenFilter.Length
? "All files (*.*)|*.*"
: m_sFileOpenFilter
};
if(DialogResult.OK == ofn.ShowDialog(this))
{
var sPath = Path.GetDirectoryName(ofn.FileName);
if (null != sPath)
{
if (Directory.Exists(sPath))
{
m_sCurrentDirectory = sPath;
if (OpenFormData(ofn.FileName))
{
SetLoadedFile(ofn.FileName);
return;
}
}
}
MessageBox.Show(this, "Error opening [" + ofn.FileName + "] Wrong file type?", "File Open Error");
}
}
/// <summary>
/// Initializes the open process with the file specified.
/// </summary>
/// <param name="sFileName">The file to open the data from</param>
/// <returns>true on success, false otherwise</returns>
public bool InitOpen(string sFileName)
{
if (IsOpenCanceledByDirty()) return false;
if (OpenFormData(sFileName))
{
SetLoadedFile(sFileName);
return true;
}
return false;
}
/// <summary>
/// Sets the currently loaded file and marks the state as clean
/// </summary>
/// <param name="sFileName"></param>
protected void SetLoadedFile(string sFileName)
{
m_sLoadedFile = sFileName;
Text = m_sBaseTitle + " [" + m_sLoadedFile + "]";
MarkClean();
}
/// <summary>
/// Event to associate with the OnClose event of the form
/// </summary>
/// <param name="eArg"></param>
protected void SaveOnClose(CancelEventArgs eArg)
{
SaveOnEvent(eArg, true);
}
protected void SaveOnEvent(CancelEventArgs eArg, bool bAllowCancel)
{
if (Dirty)
{
switch (MessageBox.Show(this, "Would you like to save any changes?",
"Save",
(bAllowCancel ? MessageBoxButtons.YesNoCancel : MessageBoxButtons.YesNo),
MessageBoxIcon.Question))
{
case DialogResult.Yes:
InitSave(false);
break;
case DialogResult.No:
MarkClean();
break;
case DialogResult.Cancel:
eArg.Cancel = true;
break;
}
}
}
/// <summary>
/// Initializes the Save / Save As dialog
/// </summary>
/// <param name="bForceSaveAs"></param>
public void InitSave(bool bForceSaveAs)
{
if (string.IsNullOrEmpty(m_sLoadedFile) || bForceSaveAs)
{
var sfn = new SaveFileDialog
{
InitialDirectory = GetDialogDirectory(),
OverwritePrompt = true,
Filter = 0 == m_sFileOpenFilter.Length
? "All files (*.*)|*.*"
: m_sFileOpenFilter
};
if (DialogResult.OK == sfn.ShowDialog(this))
{
var sPath = Path.GetDirectoryName(sfn.FileName);
if (null != sPath)
{
if (Directory.Exists(sPath))
{
m_sCurrentDirectory = sPath;
SetLoadedFile(sfn.FileName);
}
}
}
else
{
return;
}
}
if (!SaveFormData(m_sLoadedFile))
{
MessageBox.Show(this, "Error saving to file: " + m_sLoadedFile, "File Save Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MarkClean();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Windows.Forms;
namespace SIL.Windows.Forms.Widgets
{
[ProvideProperty("Prompt", typeof (Control))]
public class Prompt: Component, IExtenderProvider
{
private readonly Dictionary<Control, PromptPainter> _extendees;
public Prompt()
{
_extendees = new Dictionary<Control, PromptPainter>();
}
#region IExtenderProvider Members
public bool CanExtend(object extendee)
{
VerifyNotDisposed();
return extendee is TextBoxBase;
}
#endregion
[DefaultValue("")]
public string GetPrompt(Control c)
{
if (c == null)
{
throw new ArgumentNullException();
}
if (!CanExtend(c))
{
throw new ArgumentException("Control must be derived from TextBoxBase");
}
PromptPainter value;
if (_extendees.TryGetValue(c, out value))
{
return value.Prompt;
}
return string.Empty;
}
public void SetPrompt(Control c, string value)
{
if (c == null)
{
throw new ArgumentNullException();
}
if (!CanExtend(c))
{
throw new ArgumentException("Control must be derived from TextBoxBase");
}
if (String.IsNullOrEmpty(value))
{
_extendees.Remove(c);
}
else
{
if (_extendees.ContainsKey(c))
{
_extendees[c].Prompt = value;
}
else
{
_extendees[c] = new PromptPainter(c, value);
}
}
}
public bool GetIsPromptVisible(Control c)
{
if (c == null)
{
throw new ArgumentNullException();
}
if (!CanExtend(c))
{
throw new ArgumentException("Control must be derived from TextBoxBase");
}
PromptPainter value;
if (_extendees.TryGetValue(c, out value))
{
return value.ShouldShowPrompt(c);
}
return false;
}
#region IComponent Members
public event EventHandler Disposed = delegate
{ };
private ISite site;
public ISite Site
{
get
{
VerifyNotDisposed();
return site;
}
set
{
VerifyNotDisposed();
site = value;
}
}
private bool _isDisposed = false;
public void Dispose()
{
if (!_isDisposed)
{
_isDisposed = true;
_extendees.Clear();
Disposed(this, new EventArgs());
}
}
private void VerifyNotDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
#endregion
#region Nested type: PromptPainter
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private class PromptPainter: NativeWindow, IDisposable
{
private readonly Control _control;
private bool _hasFocus;
private string _prompt;
public PromptPainter(Control c, string prompt)
{
if (c.IsHandleCreated)
{
AssignHandle(c.Handle);
}
c.HandleCreated += ControlHandleCreated;
c.HandleDestroyed += ControlHandleDestroyed;
_control = c;
Prompt = prompt;
}
private void ControlHandleCreated(object sender, EventArgs e)
{
AssignHandle(((Control)sender).Handle);
}
private void ControlHandleDestroyed(object sender, EventArgs e)
{
ReleaseHandle();
}
public string Prompt
{
get { return _prompt; }
set { _prompt = value; }
}
public bool Focused
{
get
{
return _hasFocus;
}
}
protected override void WndProc(ref Message m)
{
const int WM_PAINT = 0xF;
const int WM_SETFOCUS = 0x7;
const int WM_KILLFOCUS = 0x8;
base.WndProc(ref m);
switch (m.Msg)
{
case WM_SETFOCUS:
_hasFocus = true;
_control.Invalidate();
break;
case WM_KILLFOCUS:
_hasFocus = false;
_control.Invalidate();
break;
case WM_PAINT:
OnWmPaint();
break;
}
}
private void OnWmPaint()
{
if (ShouldShowPrompt(_control))
{
using (Graphics g = (_control is ComboBox)?_control.CreateGraphics():Graphics.FromHwnd(Handle))
{
TextFormatFlags flags = GetTextFormatFlags(_control);
Rectangle bounds = _control.ClientRectangle;
bounds.Inflate(-1, 0);
TextRenderer.DrawText(g,
Prompt,
_control.Font,
bounds,
SystemColors.GrayText,
_control.BackColor,
flags);
}
}
}
private static TextFormatFlags GetTextFormatFlags(Control c)
{
TextFormatFlags flags = TextFormatFlags.TextBoxControl | TextFormatFlags.NoPadding |
TextFormatFlags.WordBreak;
HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left;
TextBox textbox = c as TextBox;
if (textbox != null)
{
horizontalAlignment = textbox.TextAlign;
}
else
{
RichTextBox richtextbox = c as RichTextBox;
if (richtextbox != null)
{
horizontalAlignment = richtextbox.SelectionAlignment;
}
}
switch (horizontalAlignment)
{
case HorizontalAlignment.Center:
flags |= TextFormatFlags.HorizontalCenter;
break;
case HorizontalAlignment.Left:
flags |= TextFormatFlags.Left;
break;
case HorizontalAlignment.Right:
flags |= TextFormatFlags.Right;
break;
}
if (IsControlRightToLeft(c))
{
flags |= TextFormatFlags.RightToLeft;
}
return flags;
}
public bool ShouldShowPrompt(Control c)
{
return (!Focused && String.IsNullOrEmpty(c.Text));
}
private static bool IsControlRightToLeft(Control control)
{
while (control != null)
{
switch (control.RightToLeft)
{
case RightToLeft.Yes:
return true;
case RightToLeft.No:
return false;
case RightToLeft.Inherit:
control = control.Parent;
break;
}
}
return false;
}
#region IDisposable Members
private bool _disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// dispose-only, i.e. non-finalizable logic
_control.HandleCreated -= ControlHandleCreated;
_control.HandleDestroyed -= ControlHandleDestroyed;
if(Handle != IntPtr.Zero)
{
ReleaseHandle();
}
}
// shared (dispose and finalizable) cleanup logic
this._disposed = true;
}
}
#endregion
}
#endregion
}
}
| |
using System;
namespace UnityEngine.EventSystems
{
[AddComponentMenu("Event/Standalone Input Module")]
public class StandaloneInputModule : PointerInputModule
{
private float m_NextAction;
private Vector2 m_LastMousePosition;
private Vector2 m_MousePosition;
protected StandaloneInputModule()
{ }
[Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
public enum InputMode
{
Mouse,
Buttons
}
[Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
public InputMode inputMode
{
get { return InputMode.Mouse; }
}
[SerializeField]
private string m_HorizontalAxis = "Horizontal";
/// <summary>
/// Name of the vertical axis for movement (if axis events are used).
/// </summary>
[SerializeField]
private string m_VerticalAxis = "Vertical";
/// <summary>
/// Name of the submit button.
/// </summary>
[SerializeField]
private string m_SubmitButton = "Submit";
/// <summary>
/// Name of the submit button.
/// </summary>
[SerializeField]
private string m_CancelButton = "Cancel";
[SerializeField]
private float m_InputActionsPerSecond = 10;
[SerializeField]
private bool m_AllowActivationOnMobileDevice;
public bool allowActivationOnMobileDevice
{
get { return m_AllowActivationOnMobileDevice; }
set { m_AllowActivationOnMobileDevice = value; }
}
public float inputActionsPerSecond
{
get { return m_InputActionsPerSecond; }
set { m_InputActionsPerSecond = value; }
}
/// <summary>
/// Name of the horizontal axis for movement (if axis events are used).
/// </summary>
public string horizontalAxis
{
get { return m_HorizontalAxis; }
set { m_HorizontalAxis = value; }
}
/// <summary>
/// Name of the vertical axis for movement (if axis events are used).
/// </summary>
public string verticalAxis
{
get { return m_VerticalAxis; }
set { m_VerticalAxis = value; }
}
public string submitButton
{
get { return m_SubmitButton; }
set { m_SubmitButton = value; }
}
public string cancelButton
{
get { return m_CancelButton; }
set { m_CancelButton = value; }
}
public override void UpdateModule()
{
m_LastMousePosition = m_MousePosition;
m_MousePosition = Input.mousePosition;
}
public override bool IsModuleSupported()
{
// Check for mouse presence instead of whether touch is supported,
// as you can connect mouse to a tablet and in that case we'd want
// to use StandaloneInputModule for non-touch input events.
return m_AllowActivationOnMobileDevice || Input.mousePresent;
}
public override bool ShouldActivateModule()
{
if (!base.ShouldActivateModule())
return false;
var shouldActivate = Input.GetButtonDown(m_SubmitButton);
shouldActivate |= Input.GetButtonDown(m_CancelButton);
shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_HorizontalAxis), 0.0f);
shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_VerticalAxis), 0.0f);
shouldActivate |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f;
shouldActivate |= Input.GetMouseButtonDown(0);
return shouldActivate;
}
public override void ActivateModule()
{
base.ActivateModule();
m_MousePosition = Input.mousePosition;
m_LastMousePosition = Input.mousePosition;
var toSelect = eventSystem.currentSelectedGameObject;
if (toSelect == null)
toSelect = eventSystem.lastSelectedGameObject;
if (toSelect == null)
toSelect = eventSystem.firstSelectedGameObject;
eventSystem.SetSelectedGameObject(toSelect, GetBaseEventData());
}
public override void DeactivateModule()
{
base.DeactivateModule();
ClearSelection();
}
public override void Process()
{
bool usedEvent = SendUpdateEventToSelectedObject();
if (eventSystem.sendNavigationEvents)
{
if (!usedEvent)
usedEvent |= SendMoveEventToSelectedObject();
if (!usedEvent)
SendSubmitEventToSelectedObject();
}
ProcessMouseEvent();
}
/// <summary>
/// Process submit keys.
/// </summary>
private bool SendSubmitEventToSelectedObject()
{
if (eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
if (Input.GetButtonDown(m_SubmitButton))
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler);
if (Input.GetButtonDown(m_CancelButton))
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler);
return data.used;
}
private bool AllowMoveEventProcessing(float time)
{
bool allow = Input.GetButtonDown(m_HorizontalAxis);
allow |= Input.GetButtonDown(m_VerticalAxis);
allow |= (time > m_NextAction);
return allow;
}
private Vector2 GetRawMoveVector()
{
Vector2 move = Vector2.zero;
move.x = Input.GetAxisRaw(m_HorizontalAxis);
move.y = Input.GetAxisRaw(m_VerticalAxis);
if (Input.GetButtonDown(m_HorizontalAxis))
{
if (move.x < 0)
move.x = -1f;
if (move.x > 0)
move.x = 1f;
}
if (Input.GetButtonDown(m_VerticalAxis))
{
if (move.y < 0)
move.y = -1f;
if (move.y > 0)
move.y = 1f;
}
return move;
}
/// <summary>
/// Process keyboard events.
/// </summary>
private bool SendMoveEventToSelectedObject()
{
float time = Time.unscaledTime;
if (!AllowMoveEventProcessing(time))
return false;
Vector2 movement = GetRawMoveVector();
// Debug.Log(m_ProcessingEvent.rawType + " axis:" + m_AllowAxisEvents + " value:" + "(" + x + "," + y + ")");
var axisEventData = GetAxisEventData(movement.x, movement.y, 0.6f);
if (!Mathf.Approximately(axisEventData.moveVector.x, 0f)
|| !Mathf.Approximately(axisEventData.moveVector.y, 0f))
{
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler);
}
m_NextAction = time + 1f / m_InputActionsPerSecond;
return axisEventData.used;
}
/// <summary>
/// Process all mouse events.
/// </summary>
private void ProcessMouseEvent()
{
var mouseData = GetMousePointerEventData();
var pressed = mouseData.AnyPressesThisFrame();
var released = mouseData.AnyReleasesThisFrame();
var leftButtonData = mouseData.GetButtonState(PointerEventData.InputButton.Left).eventData;
if (!UseMouse(pressed, released, leftButtonData.buttonData))
return;
// Process the first mouse button fully
ProcessMousePress(leftButtonData);
ProcessMove(leftButtonData.buttonData);
ProcessDrag(leftButtonData.buttonData);
// Now process right / middle clicks
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData.buttonData);
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData.buttonData);
if (!Mathf.Approximately(leftButtonData.buttonData.scrollDelta.sqrMagnitude, 0.0f))
{
var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(leftButtonData.buttonData.pointerCurrentRaycast.gameObject);
ExecuteEvents.ExecuteHierarchy(scrollHandler, leftButtonData.buttonData, ExecuteEvents.scrollHandler);
}
}
private static bool UseMouse(bool pressed, bool released, PointerEventData pointerData)
{
if (pressed || released || pointerData.IsPointerMoving() || pointerData.IsScrolling())
return true;
return false;
}
private bool SendUpdateEventToSelectedObject()
{
if (eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler);
return data.used;
}
/// <summary>
/// Process the current mouse press.
/// </summary>
private void ProcessMousePress(MouseButtonEventData data)
{
var pointerEvent = data.buttonData;
var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
// PointerDown notification
if (data.PressedThisFrame())
{
pointerEvent.eligibleForClick = true;
pointerEvent.delta = Vector2.zero;
pointerEvent.dragging = false;
pointerEvent.useDragThreshold = true;
pointerEvent.pressPosition = pointerEvent.position;
pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
DeselectIfSelectionChanged(currentOverGo, pointerEvent);
// search for the control that will receive the press
// if we can't find a press handler set the press
// handler to be what would receive a click.
var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
// didnt find a press handler... search for a click handler
if (newPressed == null)
newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// Debug.Log("Pressed: " + newPressed);
float time = Time.unscaledTime;
if (newPressed == pointerEvent.lastPress)
{
var diffTime = time - pointerEvent.clickTime;
if (diffTime < 0.3f)
++pointerEvent.clickCount;
else
pointerEvent.clickCount = 1;
pointerEvent.clickTime = time;
}
else
{
pointerEvent.clickCount = 1;
}
pointerEvent.pointerPress = newPressed;
pointerEvent.rawPointerPress = currentOverGo;
pointerEvent.clickTime = time;
// Save the drag handler as well
pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
if (pointerEvent.pointerDrag != null)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
}
// PointerUp notification
if (data.ReleasedThisFrame())
{
// Debug.Log("Executing pressup on: " + pointer.pointerPress);
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
// Debug.Log("KeyCode: " + pointer.eventData.keyCode);
// see if we mouse up on the same element that we clicked on...
var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// PointerClick and Drop events
if (pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
}
else if (pointerEvent.pointerDrag != null)
{
ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
}
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
if (pointerEvent.pointerDrag != null && pointerEvent.dragging)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
pointerEvent.dragging = false;
pointerEvent.pointerDrag = null;
// redo pointer enter / exit to refresh state
// so that if we moused over somethign that ignored it before
// due to having pressed on something else
// it now gets it.
if (currentOverGo != pointerEvent.pointerEnter)
{
HandlePointerExitAndEnter(pointerEvent, null);
HandlePointerExitAndEnter(pointerEvent, currentOverGo);
}
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Config;
namespace NLog.UnitTests.LayoutRenderers
{
using Xunit;
public class NDCTests : NLogTestBase
{
[Fact]
public void NDCTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala ma kota c");
using (NestedDiagnosticsContext.Push("kopytko"))
{
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "ala ma kota kopytko d");
}
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala ma kota c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
}
[Fact]
public void NDCTopTestTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc:topframes=2} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ma kota c");
using (NestedDiagnosticsContext.Push("kopytko"))
{
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "kota kopytko d");
}
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ma kota c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
}
[Fact]
public void NDCTop1TestTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc:topframes=1} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "kota c");
NestedDiagnosticsContext.Push("kopytko");
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "kopytko d");
Assert.Equal("kopytko", NestedDiagnosticsContext.Pop()); // manual pop
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "kota c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop());
Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage);
NestedDiagnosticsContext.Push("zzz");
Assert.Equal("zzz", NestedDiagnosticsContext.TopMessage);
NestedDiagnosticsContext.Clear();
Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop());
Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage);
}
[Fact]
public void NDCBottomTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc:bottomframes=2} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala ma c");
using (NestedDiagnosticsContext.Push("kopytko"))
{
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "ala ma d");
}
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala ma c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
}
[Fact]
public void NDCSeparatorTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc:separator=\:} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala:ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala:ma:kota c");
using (NestedDiagnosticsContext.Push("kopytko"))
{
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "ala:ma:kota:kopytko d");
}
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala:ma:kota c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala:ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Testing;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class ViewEngineTests : IClassFixture<MvcTestFixture<RazorWebSite.Startup>>
{
private static readonly Assembly _assembly = typeof(ViewEngineTests).GetTypeInfo().Assembly;
public ViewEngineTests(MvcTestFixture<RazorWebSite.Startup> fixture)
{
Client = fixture.CreateDefaultClient();
}
public HttpClient Client { get; }
public static IEnumerable<object[]> RazorView_ExecutesPageAndLayoutData
{
get
{
yield return new[] { "ViewWithoutLayout", @"ViewWithoutLayout-Content" };
yield return new[]
{
"ViewWithLayout",
@"<layout>
ViewWithLayout-Content
</layout>"
};
yield return new[]
{
"ViewWithFullPath",
@"<layout>
ViewWithFullPath-content
</layout>"
};
yield return new[]
{
"ViewWithNestedLayout",
@"<layout>
<nested-layout>
/ViewEngine/ViewWithNestedLayout
ViewWithNestedLayout-Content
</nested-layout>
</layout>"
};
yield return new[]
{
"ViewWithDataFromController",
"<h1>hello from controller</h1>"
};
}
}
[Theory]
[MemberData(nameof(RazorView_ExecutesPageAndLayoutData))]
public async Task RazorView_ExecutesPageAndLayout(string actionName, string expected)
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ViewEngine/" + actionName);
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task RazorView_ExecutesPartialPagesWithCorrectContext()
{
// Arrange
var expected = @"<partial>98052
</partial>
<partial2>98052
</partial2>
test-value";
// Act
var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithPartial");
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task RazorView_DoesNotThrow_PartialViewWithEnumerableModel()
{
// Arrange
var expected = "HelloWorld";
// Act
var body = await Client.GetStringAsync(
"http://localhost/ViewEngine/ViewWithPartialTakingModelFromIEnumerable");
// Assert
Assert.Equal(expected, body.Trim());
}
[Fact]
public async Task RazorView_PassesViewContextBetweenViewAndLayout()
{
// Arrange
var expected =
@"<title>Page title</title>
partial-contentcomponent-content";
// Act
var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewPassesViewDataToLayout");
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
public static IEnumerable<object[]> RazorViewEngine_UsesAllExpandedPathsToLookForViewsData
{
get
{
var expected1 = @"expander-index
gb-partial";
yield return new[] { "en-GB", expected1 };
var expected2 = @"fr-index
fr-partial";
yield return new[] { "fr", expected2 };
if (!TestPlatformHelper.IsMono)
{
// https://github.com/aspnet/Mvc/issues/2759
var expected3 = @"expander-index
expander-partial";
yield return new[] { "!-invalid-!", expected3 };
}
}
}
[Theory]
[MemberData(nameof(RazorViewEngine_UsesAllExpandedPathsToLookForViewsData))]
public async Task RazorViewEngine_UsesViewExpandersForViewsAndPartials(string value, string expected)
{
// Arrange
var cultureCookie = "c=" + value + "|uic=" + value;
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TemplateExpander");
request.Headers.Add("Cookie",
new CookieHeaderValue(CookieRequestCultureProvider.DefaultCookieName, cultureCookie).ToString());
// Act
var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
public static TheoryData ViewLocationExpanders_GetIsMainPageFromContextData
{
get
{
return new TheoryData<string, string>
{
{
"Index",
"<expander-view><shared-views>/Shared-Views/ExpanderViews/_ExpanderPartial.cshtml</shared-views></expander-view>"
},
{
"Partial",
"<shared-views>/Shared-Views/ExpanderViews/_ExpanderPartial.cshtml</shared-views>"
},
};
}
}
[Theory]
[MemberData(nameof(ViewLocationExpanders_GetIsMainPageFromContextData))]
public async Task ViewLocationExpanders_GetIsMainPageFromContext(string action, string expected)
{
// Arrange & Act
var body = await Client.GetStringAsync($"http://localhost/ExpanderViews/{action}");
// Assert
Assert.Equal(expected, body.Trim());
}
public static IEnumerable<object[]> RazorViewEngine_RendersPartialViewsData
{
get
{
yield return new[]
{
"ViewWithoutLayout", "ViewWithoutLayout-Content"
};
yield return new[]
{
"PartialViewWithNamePassedIn",
@"<layout>
ViewWithLayout-Content
</layout>"
};
yield return new[]
{
"ViewWithFullPath",
@"<layout>
ViewWithFullPath-content
</layout>"
};
yield return new[]
{
"ViewWithNestedLayout",
@"<layout>
<nested-layout>
/PartialViewEngine/ViewWithNestedLayout
ViewWithNestedLayout-Content
</nested-layout>
</layout>"
};
yield return new[]
{
"PartialWithDataFromController", "<h1>hello from controller</h1>"
};
yield return new[]
{
"PartialWithModel",
@"my name is judge
<partial>98052
</partial>"
};
}
}
[Theory]
[MemberData(nameof(RazorViewEngine_RendersPartialViewsData))]
public async Task RazorViewEngine_RendersPartialViews(string actionName, string expected)
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/PartialViewEngine/" + actionName);
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task LayoutValueIsPassedBetweenNestedViewStarts()
{
// Arrange
var expected = @"<title>viewstart-value</title>
~/Views/NestedViewStarts/NestedViewStarts/Layout.cshtml
index-content";
// Act
var body = await Client.GetStringAsync("http://localhost/NestedViewStarts");
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
public static IEnumerable<object[]> RazorViewEngine_UsesExpandersForLayoutsData
{
get
{
var expected1 =
@"<language-layout>View With Layout
</language-layout>";
yield return new[] { "en-GB", expected1 };
if (!TestPlatformHelper.IsMono)
{
// https://github.com/aspnet/Mvc/issues/2759
yield return new[] { "!-invalid-!", expected1 };
}
var expected2 =
@"<fr-language-layout>View With Layout
</fr-language-layout>";
yield return new[] { "fr", expected2 };
}
}
[Theory]
[MemberData(nameof(RazorViewEngine_UsesExpandersForLayoutsData))]
public async Task RazorViewEngine_UsesExpandersForLayouts(string value, string expected)
{
// Arrange
var cultureCookie = "c=" + value + "|uic=" + value;
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TemplateExpander/ViewWithLayout");
request.Headers.Add("Cookie",
new CookieHeaderValue(CookieRequestCultureProvider.DefaultCookieName, cultureCookie).ToString());
// Act
var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task ViewStartsCanUseDirectivesInjectedFromParentGlobals()
{
// Arrange
var expected =
@"<view-start>Hello Controller-Person</view-start>
<page>Hello Controller-Person</page>";
var target = "http://localhost/NestedViewImports";
// Act
var body = await Client.GetStringAsync(target);
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task ViewComponentsExecuteLayout()
{
// Arrange
var expected =
@"<title>View With Component With Layout</title>
Page Content
<component-title>ViewComponent With Title</component-title>
<component-body>Component With Layout</component-body>";
// Act
var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasLayout");
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task RelativePathsWorkAsExpected()
{
// Arrange
var expected =
@"<layout>
<nested-layout>
/ViewEngine/ViewWithRelativePath
ViewWithRelativePath-content
<partial>partial-content</partial>
<component-title>View with relative path title</component-title>
<component-body>Component with Relative Path
<label><strong>Name:</strong> Fred</label>
WriteLiteral says:<strong>Write says:98052WriteLiteral says:</strong></component-body>
</nested-layout>
</layout>";
// Act
var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithRelativePath");
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task ViewComponentsDoNotExecuteViewStarts()
{
// Arrange
var expected = @"<page-content>ViewComponent With ViewStart</page-content>";
// Act
var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasViewStart");
// Assert
Assert.Equal(expected, body.Trim());
}
[Fact]
public async Task PartialDoNotExecuteViewStarts()
{
// Arrange
var expected = "Partial that does not specify Layout";
// Act
var body = await Client.GetStringAsync("http://localhost/PartialsWithLayout/PartialDoesNotExecuteViewStarts");
// Assert
Assert.Equal(expected, body.Trim());
}
[Fact]
public async Task PartialsRenderedViaRenderPartialAsync_CanRenderLayouts()
{
// Arrange
var expected =
@"<layout-for-viewstart-with-layout><layout-for-viewstart-with-layout>Partial that specifies Layout
</layout-for-viewstart-with-layout>Partial that does not specify Layout</layout-for-viewstart-with-layout>";
// Act
var body = await Client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaRenderPartial");
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task PartialsRenderedViaPartialAsync_CanRenderLayouts()
{
// Arrange
var expected =
@"<layout-for-viewstart-with-layout><layout-for-viewstart-with-layout>Partial that specifies Layout
</layout-for-viewstart-with-layout>
Partial that does not specify Layout
</layout-for-viewstart-with-layout>";
// Act
var response = await Client.GetAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaPartial");
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
public async Task RazorView_SetsViewPathAndExecutingPagePath()
{
// Arrange
var outputFile = "compiler/resources/ViewEngineController.ViewWithPaths.txt";
var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false);
// Act
var responseContent = await Client.GetStringAsync("http://localhost/ViewWithPaths");
// Assert
responseContent = responseContent.Trim();
ResourceFile.UpdateOrVerify(_assembly, outputFile, expectedContent, responseContent);
}
[Fact]
public async Task ViewEngine_NormalizesPathsReturnedByViewLocationExpanders()
{
// Arrange
var expected =
@"Layout
Page
Partial";
// Act
var responseContent = await Client.GetStringAsync("/BackSlash");
// Assert
Assert.Equal(expected, responseContent, ignoreLineEndingDifferences: true);
}
[Fact]
public async Task ViewEngine_DiscoversViewsFromPagesSharedDirectory()
{
// Arrange
var expected = "Hello from Pages/Shared";
// Act
var responseContent = await Client.GetStringAsync("/ViewEngine/SearchInPages");
// Assert
Assert.Equal(expected, responseContent.Trim());
}
}
}
| |
namespace dotless.Test.Specs
{
using NUnit.Framework;
public class MixinsArgsFixture : SpecFixtureBase
{
[Test]
public void MixinsArgsHidden1()
{
var input =
@"
.hidden() {
color: transparent;
}
#hidden {
.hidden();
}
";
var expected =
@"
#hidden {
color: transparent;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsHidden2()
{
var input =
@"
.hidden() {
color: transparent;
}
#hidden {
.hidden;
}
";
var expected =
@"
#hidden {
color: transparent;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsTwoArgs()
{
var input =
@"
.mixin (@a: 1px, @b: 50%) {
width: @a * 5;
height: @b - 1%;
}
.mixina (@style, @width, @color: black) {
border: @width @style @color;
}
.two-args {
color: blue;
.mixin(2px, 100%);
.mixina(dotted, 2px);
}
";
var expected =
@"
.two-args {
color: blue;
width: 10px;
height: 99%;
border: 2px dotted black;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinCallWithSemiColonSeparator()
{
// MixinsArgsTwoArgs_with_semi_colon_separator tests the a MixinDefinition will support semicolon-separated arguments while this
// test that a MixinCall will support them
var input = @".size(@width, @height) {
width: @width;
height: @height;
}
.container {
.size(100px; 50px);
}";
var expected = @".container {
width: 100px;
height: 50px;
}";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsTwoArgs_with_semi_colon_separator()
{
var input =
@"
.mixin (@a: 1px; @b: 50%) {
width: @a * 5;
height: @b - 1%;
}
.mixina (@style, @width, @color: black) {
border: @width @style @color;
}
.two-args {
color: blue;
.mixin(2px, 100%);
.mixina(dotted, 2px);
}
";
var expected =
@"
.two-args {
color: blue;
width: 10px;
height: 99%;
border: 2px dotted black;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinCallError()
{
var input =
@"
.mixin (@a, @b) {
width: @a;
height: @b;
}
@c: 1px;
.one-arg {
.mixin(@c);
}
";
AssertError(@"
No matching definition was found for `.mixin(1px)` on line 9 in file 'test.less':
[8]: .one-arg {
[9]: .mixin(@c);
--^
[10]: }", input);
}
[Test]
public void MixinsArgsOneArg()
{
// Todo: split into separate atomic tests.
var input =
@"
.mixin (@a: 1px, @b: 50%) {
width: @a * 5;
height: @b - 1%;
}
.one-arg {
.mixin(3px);
}
";
var expected =
@"
.one-arg {
width: 15px;
height: 49%;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsNoParens()
{
var input =
@"
.mixin (@a: 1px, @b: 50%) {
width: @a * 5;
height: @b - 1%;
}
.no-parens {
.mixin;
}
";
var expected =
@"
.no-parens {
width: 5px;
height: 49%;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsNoArgs()
{
var input =
@"
.mixin (@a: 1px, @b: 50%) {
width: @a * 5;
height: @b - 1%;
}
.no-args {
.mixin();
}
";
var expected =
@"
.no-args {
width: 5px;
height: 49%;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsVariableArgs()
{
var input =
@"
.mixin (@a: 1px, @b: 50%) {
width: @a * 5;
height: @b - 1%;
}
.var-args {
@var: 9;
.mixin(@var, @var * 2);
}
";
var expected =
@"
.var-args {
width: 45;
height: 17%;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsMulti()
{
var input =
@"
.mixin (@a: 1px, @b: 50%) {
width: @a * 5;
height: @b - 1%;
}
.mixiny
(@a: 0, @b: 0) {
margin: @a;
padding: @b;
}
.multi-mix {
.mixin(2px, 30%);
.mixiny(4, 5);
}
";
var expected =
@"
.multi-mix {
width: 10px;
height: 29%;
margin: 4;
padding: 5;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgs()
{
var input =
@"
.maxa(@arg1: 10, @arg2: #f00) {
padding: @arg1 * 2px;
color: @arg2;
}
body {
.maxa(15);
}
";
var expected =
@"
body {
padding: 30px;
color: #f00;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsScopeMix()
{
var input =
@"
@glob: 5;
.global-mixin(@a:2) {
width: @glob + @a;
}
.scope-mix {
.global-mixin(3);
}
";
var expected =
@"
.scope-mix {
width: 8;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinsArgsNestedRuleset()
{
var input =
@"
.nested-ruleset (@width: 200px) {
width: @width;
.column { margin: @width; }
}
.content {
.nested-ruleset(600px);
}
";
var expected =
@"
.content {
width: 600px;
}
.content .column {
margin: 600px;
}
";
AssertLess(input, expected);
}
[Test]
public void CanEvaluateCommaSepearatedExpressions()
{
var input =
@"
.fonts (@main: 'Arial') {
font-family: @main, sans-serif;
}
.class {
.fonts('Helvetica');
}";
var expected = @"
.class {
font-family: 'Helvetica', sans-serif;
}";
AssertLess(input, expected);
}
[Test]
public void CanUseVariablesInsideMixins()
{
var input = @"
@var: 5px;
.mixin() {
width: @var, @var, @var;
}
.div {
.mixin;
}";
var expected = @"
.div {
width: 5px, 5px, 5px;
}";
AssertLess(input, expected);
}
[Test]
public void CanUseSameVariableName()
{
var input =
@"
.same-var-name2(@radius) {
radius: @radius;
}
.same-var-name(@radius) {
.same-var-name2(@radius);
}
#same-var-name {
.same-var-name(5px);
}
";
var expected = @"
#same-var-name {
radius: 5px;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinArgsHashMixin1()
{
var input = @"
#id-mixin () {
color: red;
}
.id-class {
#id-mixin();
}
";
var expected = @"
.id-class {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinArgsHashMixin2()
{
var input = @"
#id-mixin () {
color: red;
}
.id-class {
#id-mixin;
}
";
var expected = @"
.id-class {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void MixinArgsExceptCurlyBracketString()
{
var input =
@"
.mixin-arguments (@width: 0px) {
border: @arguments;
}
.arguments2 {
.mixin-arguments(""{"");
}";
var expected = @"
.arguments2 {
border: ""{"";
}";
AssertLess(input, expected);
}
[Test]
public void VariadicArgs1()
{
var input = @"
.mixin-arguments (@width: 0px, ...) {
border: @arguments;
width: @width;
}
.arguments {
.mixin-arguments(1px, solid, black);
}
.arguments2 {
.mixin-arguments();
}
.arguments3 {
.mixin-arguments;
}";
var expected = @"
.arguments {
border: 1px solid black;
width: 1px;
}
.arguments2 {
border: 0px;
width: 0px;
}
.arguments3 {
border: 0px;
width: 0px;
}";
AssertLess(input, expected);
}
[Test]
public void VariadicArgs2()
{
var input = @"
.mixin-arguments2 (@width, @rest...) {
border: @arguments;
rest: @rest;
width: @width;
}
.arguments4 {
.mixin-arguments2(0, 1, 2, 3, 4);
}";
var expected = @"
.arguments4 {
border: 0 1 2 3 4;
rest: 1 2 3 4;
width: 0;
}";
AssertLess(input, expected);
}
[Test]
public void VariadicArgs3a()
{
var input = @"
.mixin (...) {
variadic: true;
}
.mixin () {
zero: 0;
}
.mixin (@a: 1px) {
one: 1;
}
.mixin (@a) {
one-req: 1;
}
.mixin (@a: 1px, @b: 2px) {
two: 2;
}
.mixin (@a, @b, @c) {
three-req: 3;
}
.mixin (@a: 1px, @b: 2px, @c: 3px) {
three: 3;
}
.zero {
.mixin();
}
";
var expected = @"
.zero {
variadic: true;
zero: 0;
one: 1;
two: 2;
three: 3;
}";
AssertLess(input, expected);
}
[Test]
public void VariadicArgs3b()
{
var input = @"
.mixin (...) {
variadic: true;
}
.mixin () {
zero: 0;
}
.mixin (@a: 1px) {
one: 1;
}
.mixin (@a) {
one-req: 1;
}
.mixin (@a: 1px, @b: 2px) {
two: 2;
}
.mixin (@a, @b, @c) {
three-req: 3;
}
.mixin (@a: 1px, @b: 2px, @c: 3px) {
three: 3;
}
.one {
.mixin(1);
}
";
var expected = @"
.one {
variadic: true;
one: 1;
one-req: 1;
two: 2;
three: 3;
}";
AssertLess(input, expected);
}
[Test]
public void VariadicArgs3c()
{
var input = @"
.mixin (...) {
variadic: true;
}
.mixin () {
zero: 0;
}
.mixin (@a: 1px) {
one: 1;
}
.mixin (@a) {
one-req: 1;
}
.mixin (@a: 1px, @b: 2px) {
two: 2;
}
.mixin (@a, @b, @c) {
three-req: 3;
}
.mixin (@a: 1px, @b: 2px, @c: 3px) {
three: 3;
}
.two {
.mixin(1, 2);
}";
var expected = @"
.two {
variadic: true;
two: 2;
three: 3;
}
";
AssertLess(input, expected);
}
[Test]
public void VariadicArgs3d()
{
var input = @"
.mixin (...) {
variadic: true;
}
.mixin () {
zero: 0;
}
.mixin (@a: 1px) {
one: 1;
}
.mixin (@a) {
one-req: 1;
}
.mixin (@a: 1px, @b: 2px) {
two: 2;
}
.mixin (@a, @b, @c) {
three-req: 3;
}
.mixin (@a: 1px, @b: 2px, @c: 3px) {
three: 3;
}
.three {
.mixin(1, 2, 3);
}";
var expected = @"
.three {
variadic: true;
three-req: 3;
three: 3;
}";
AssertLess(input, expected);
}
#region GitHub issue 408
/// <summary>
/// This is the failure case reported at https://github.com/dotless/dotless/issues/408
/// </summary>
[Test]
public void ExpressionArguments() {
var input = @"@tilebasewidth : 130px;
@tilemargin: 10px;
.test(@param1, @param2) {
width: @param1;
height: @param2;
}
.two-c {
.test(@tilebasewidth, (@tilebasewidth + @tilemargin)*2);
}";
var expected = @".two-c {
width: 130px;
height: 280px;
}";
AssertLess(input, expected);
}
/// <summary>
/// This case actually worked before, too. Included here to ensure that fixing one case doesn't break another.
/// </summary>
[Test]
public void ExpressionArguments2() {
var input = @"@tilebasewidth : 130px;
@tilemargin: 10px;
.test(@param1, @param2) {
width: @param1;
height: @param2;
}
.two-c {
.test((@tilebasewidth + @tilemargin) * 2, @tilebasewidth);
}";
var expected = @".two-c {
width: 280px;
height: 130px;
}";
AssertLess(input, expected);
}
/// <summary>
/// This case actually worked before, too. Included here to ensure that fixing one case doesn't break another.
/// </summary>
[Test]
public void ExpressionArguments3() {
var input = @"@tilebasewidth : 130px;
@tilemargin: 10px;
.test(@param1, @param2) {
width: @param1;
height: @param2;
}
.two-c {
.test(5px, (@tilebasewidth + @tilemargin) * 2);
}";
var expected = @".two-c {
width: 5px;
height: 280px;
}";
AssertLess(input, expected);
}
#endregion
[Test]
public void NamedArguments() {
var input = @"
#gradient {
.horizontal(@start-color, @end-color) {
color: @start-color;
background-color: @end-color;
}
}
.test {
#gradient > .horizontal(@start-color: rgba(0,0,0,.5); @end-color: rgba(0,0,0,.0001));
}
";
var expected = @"
.test {
color: rgba(0, 0, 0, 0.5);
background-color: rgba(0, 0, 0, 0.0001);
}";
AssertLess(input, expected);
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SchoolBusAPI.Models;
namespace SchoolBusAPI.Models
{
/// <summary>
/// Demographic information about companies, organizations, school districts, or individuals who own or lease school buses
/// </summary>
[MetaDataExtension (Description = "Demographic information about companies, organizations, school districts, or individuals who own or lease school buses")]
public partial class SchoolBusOwner : AuditableEntity, IEquatable<SchoolBusOwner>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public SchoolBusOwner()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="SchoolBusOwner" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a SchoolBusOwner (required).</param>
/// <param name="Name">The name of the School Bus owner as defined by the user&#x2F;Inspector. Not tied to the ICBC or NSC names, but whatever is most useful for the Inspectors. (required).</param>
/// <param name="Status">Status of the School Bus owner - enumerated value Active, Inactive or Archived from drop down (required).</param>
/// <param name="DateCreated">The original create date and time of the owner record. The date-time of the creation of the record from the audit fields. Since this might be surfaced in the API, adding it to the definition. (required).</param>
/// <param name="PrimaryContact">Link to the designated Primary Contact for the Inspector to the School Bus Owner organization..</param>
/// <param name="District">The District to which this School Bus is affliated..</param>
/// <param name="Contacts">The set of contacts related to the School Bus Owner..</param>
/// <param name="Notes">The set of notes about the school bus owner entered by users..</param>
/// <param name="Attachments">The set of attachments about the school bus owner uploaded by the users..</param>
/// <param name="History">The history of updates made to the School Bus Owner data..</param>
public SchoolBusOwner(int Id, string Name, string Status, DateTime DateCreated, Contact PrimaryContact = null, District District = null, List<Contact> Contacts = null, List<Note> Notes = null, List<Attachment> Attachments = null, List<History> History = null)
{
this.Id = Id;
this.Name = Name;
this.Status = Status;
this.DateCreated = DateCreated;
this.PrimaryContact = PrimaryContact;
this.District = District;
this.Contacts = Contacts;
this.Notes = Notes;
this.Attachments = Attachments;
this.History = History;
}
/// <summary>
/// A system-generated unique identifier for a SchoolBusOwner
/// </summary>
/// <value>A system-generated unique identifier for a SchoolBusOwner</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a SchoolBusOwner")]
public int Id { get; set; }
/// <summary>
/// The name of the School Bus owner as defined by the user/Inspector. Not tied to the ICBC or NSC names, but whatever is most useful for the Inspectors.
/// </summary>
/// <value>The name of the School Bus owner as defined by the user/Inspector. Not tied to the ICBC or NSC names, but whatever is most useful for the Inspectors.</value>
[MetaDataExtension (Description = "The name of the School Bus owner as defined by the user/Inspector. Not tied to the ICBC or NSC names, but whatever is most useful for the Inspectors.")]
[MaxLength(150)]
public string Name { get; set; }
/// <summary>
/// Status of the School Bus owner - enumerated value Active, Inactive or Archived from drop down
/// </summary>
/// <value>Status of the School Bus owner - enumerated value Active, Inactive or Archived from drop down</value>
[MetaDataExtension (Description = "Status of the School Bus owner - enumerated value Active, Inactive or Archived from drop down")]
[MaxLength(30)]
public string Status { get; set; }
/// <summary>
/// The original create date and time of the owner record. The date-time of the creation of the record from the audit fields. Since this might be surfaced in the API, adding it to the definition.
/// </summary>
/// <value>The original create date and time of the owner record. The date-time of the creation of the record from the audit fields. Since this might be surfaced in the API, adding it to the definition.</value>
[MetaDataExtension (Description = "The original create date and time of the owner record. The date-time of the creation of the record from the audit fields. Since this might be surfaced in the API, adding it to the definition.")]
public DateTime DateCreated { get; set; }
/// <summary>
/// Link to the designated Primary Contact for the Inspector to the School Bus Owner organization.
/// </summary>
/// <value>Link to the designated Primary Contact for the Inspector to the School Bus Owner organization.</value>
[MetaDataExtension (Description = "Link to the designated Primary Contact for the Inspector to the School Bus Owner organization.")]
public Contact PrimaryContact { get; set; }
/// <summary>
/// Foreign key for PrimaryContact
/// </summary>
[ForeignKey("PrimaryContact")]
[JsonIgnore]
[MetaDataExtension (Description = "Link to the designated Primary Contact for the Inspector to the School Bus Owner organization.")]
public int? PrimaryContactId { get; set; }
/// <summary>
/// The District to which this School Bus is affliated.
/// </summary>
/// <value>The District to which this School Bus is affliated.</value>
[MetaDataExtension (Description = "The District to which this School Bus is affliated.")]
public District District { get; set; }
/// <summary>
/// Foreign key for District
/// </summary>
[ForeignKey("District")]
[JsonIgnore]
[MetaDataExtension (Description = "The District to which this School Bus is affliated.")]
public int? DistrictId { get; set; }
/// <summary>
/// The set of contacts related to the School Bus Owner.
/// </summary>
/// <value>The set of contacts related to the School Bus Owner.</value>
[MetaDataExtension (Description = "The set of contacts related to the School Bus Owner.")]
public List<Contact> Contacts { get; set; }
/// <summary>
/// The set of notes about the school bus owner entered by users.
/// </summary>
/// <value>The set of notes about the school bus owner entered by users.</value>
[MetaDataExtension (Description = "The set of notes about the school bus owner entered by users.")]
public List<Note> Notes { get; set; }
/// <summary>
/// The set of attachments about the school bus owner uploaded by the users.
/// </summary>
/// <value>The set of attachments about the school bus owner uploaded by the users.</value>
[MetaDataExtension (Description = "The set of attachments about the school bus owner uploaded by the users.")]
public List<Attachment> Attachments { get; set; }
/// <summary>
/// The history of updates made to the School Bus Owner data.
/// </summary>
/// <value>The history of updates made to the School Bus Owner data.</value>
[MetaDataExtension (Description = "The history of updates made to the School Bus Owner data.")]
public List<History> History { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class SchoolBusOwner {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" DateCreated: ").Append(DateCreated).Append("\n");
sb.Append(" PrimaryContact: ").Append(PrimaryContact).Append("\n");
sb.Append(" District: ").Append(District).Append("\n");
sb.Append(" Contacts: ").Append(Contacts).Append("\n");
sb.Append(" Notes: ").Append(Notes).Append("\n");
sb.Append(" Attachments: ").Append(Attachments).Append("\n");
sb.Append(" History: ").Append(History).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((SchoolBusOwner)obj);
}
/// <summary>
/// Returns true if SchoolBusOwner instances are equal
/// </summary>
/// <param name="other">Instance of SchoolBusOwner to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SchoolBusOwner other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.DateCreated == other.DateCreated ||
this.DateCreated != null &&
this.DateCreated.Equals(other.DateCreated)
) &&
(
this.PrimaryContact == other.PrimaryContact ||
this.PrimaryContact != null &&
this.PrimaryContact.Equals(other.PrimaryContact)
) &&
(
this.District == other.District ||
this.District != null &&
this.District.Equals(other.District)
) &&
(
this.Contacts == other.Contacts ||
this.Contacts != null &&
this.Contacts.SequenceEqual(other.Contacts)
) &&
(
this.Notes == other.Notes ||
this.Notes != null &&
this.Notes.SequenceEqual(other.Notes)
) &&
(
this.Attachments == other.Attachments ||
this.Attachments != null &&
this.Attachments.SequenceEqual(other.Attachments)
) &&
(
this.History == other.History ||
this.History != null &&
this.History.SequenceEqual(other.History)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null)
{
hash = hash * 59 + this.Name.GetHashCode();
}
if (this.Status != null)
{
hash = hash * 59 + this.Status.GetHashCode();
}
if (this.DateCreated != null)
{
hash = hash * 59 + this.DateCreated.GetHashCode();
}
if (this.PrimaryContact != null)
{
hash = hash * 59 + this.PrimaryContact.GetHashCode();
}
if (this.District != null)
{
hash = hash * 59 + this.District.GetHashCode();
}
if (this.Contacts != null)
{
hash = hash * 59 + this.Contacts.GetHashCode();
}
if (this.Notes != null)
{
hash = hash * 59 + this.Notes.GetHashCode();
}
if (this.Attachments != null)
{
hash = hash * 59 + this.Attachments.GetHashCode();
}
if (this.History != null)
{
hash = hash * 59 + this.History.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(SchoolBusOwner left, SchoolBusOwner right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(SchoolBusOwner left, SchoolBusOwner right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityTest
{
public interface ITestComponent : IComparable<ITestComponent>
{
void EnableTest(bool enable);
bool IsTestGroup();
GameObject gameObject { get; }
string Name { get; }
ITestComponent GetTestGroup();
bool IsExceptionExpected(string exceptionType);
bool ShouldSucceedOnException();
double GetTimeout();
bool IsIgnored();
bool ShouldSucceedOnAssertions();
bool IsExludedOnThisPlatform();
}
public class TestComponent : MonoBehaviour, ITestComponent
{
public static ITestComponent NullTestComponent = new NullTestComponentImpl();
public float timeout = 5;
public bool ignored = false;
public bool succeedAfterAllAssertionsAreExecuted = false;
public bool expectException = false;
public string expectedExceptionList = "";
public bool succeedWhenExceptionIsThrown = false;
public IncludedPlatforms includedPlatforms = (IncludedPlatforms) ~0L;
public string[] platformsToIgnore = null;
public bool dynamic;
public string dynamicTypeName;
public bool IsExludedOnThisPlatform()
{
return platformsToIgnore != null && platformsToIgnore.Any(platform => platform == Application.platform.ToString());
}
static bool IsAssignableFrom(Type a, Type b)
{
#if !UNITY_METRO
return a.IsAssignableFrom(b);
#else
return false;
#endif
}
public bool IsExceptionExpected(string exception)
{
exception = exception.Trim();
if (!expectException)
return false;
if(string.IsNullOrEmpty(expectedExceptionList.Trim()))
return true;
foreach (var expectedException in expectedExceptionList.Split(',').Select(e => e.Trim()))
{
if (exception == expectedException)
return true;
var exceptionType = Type.GetType(exception) ?? GetTypeByName(exception);
var expectedExceptionType = Type.GetType(expectedException) ?? GetTypeByName(expectedException);
if (exceptionType != null && expectedExceptionType != null && IsAssignableFrom(expectedExceptionType, exceptionType))
return true;
}
return false;
}
public bool ShouldSucceedOnException()
{
return succeedWhenExceptionIsThrown;
}
public double GetTimeout()
{
return timeout;
}
public bool IsIgnored()
{
return ignored;
}
public bool ShouldSucceedOnAssertions()
{
return succeedAfterAllAssertionsAreExecuted;
}
private static Type GetTypeByName(string className)
{
#if !UNITY_METRO
return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).FirstOrDefault(type => type.Name == className);
#else
return null;
#endif
}
public void OnValidate()
{
if (timeout < 0.01f) timeout = 0.01f;
}
// Legacy
[Flags]
public enum IncludedPlatforms
{
WindowsEditor = 1 << 0,
OSXEditor = 1 << 1,
WindowsPlayer = 1 << 2,
OSXPlayer = 1 << 3,
LinuxPlayer = 1 << 4,
MetroPlayerX86 = 1 << 5,
MetroPlayerX64 = 1 << 6,
MetroPlayerARM = 1 << 7,
WindowsWebPlayer = 1 << 8,
OSXWebPlayer = 1 << 9,
Android = 1 << 10,
// ReSharper disable once InconsistentNaming
IPhonePlayer = 1 << 11,
TizenPlayer = 1 << 12,
WP8Player = 1 << 13,
BB10Player = 1 << 14,
NaCl = 1 << 15,
PS3 = 1 << 16,
XBOX360 = 1 << 17,
WiiPlayer = 1 << 18,
PSP2 = 1 << 19,
PS4 = 1 << 20,
PSMPlayer = 1 << 21,
XboxOne = 1 << 22,
}
#region ITestComponent implementation
public void EnableTest(bool enable)
{
if (enable && dynamic)
{
Type t = Type.GetType(dynamicTypeName);
var s = gameObject.GetComponent(t) as MonoBehaviour;
if (s != null)
DestroyImmediate(s);
gameObject.AddComponent(t);
}
if (gameObject.activeSelf != enable) gameObject.SetActive(enable);
}
public int CompareTo(ITestComponent obj)
{
if (obj == NullTestComponent)
return 1;
var result = gameObject.name.CompareTo(obj.gameObject.name);
if (result == 0)
result = gameObject.GetInstanceID().CompareTo(obj.gameObject.GetInstanceID());
return result;
}
public bool IsTestGroup()
{
for (int i = 0; i < gameObject.transform.childCount; i++)
{
var childTc = gameObject.transform.GetChild(i).GetComponent(typeof(TestComponent));
if (childTc != null)
return true;
}
return false;
}
public string Name { get { return gameObject == null ? "" : gameObject.name; } }
public ITestComponent GetTestGroup()
{
var parent = gameObject.transform.parent;
if (parent == null)
return NullTestComponent;
return parent.GetComponent<TestComponent>();
}
public override bool Equals(object o)
{
if (o is TestComponent)
return this == (o as TestComponent);
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool operator ==(TestComponent a, TestComponent b)
{
if (ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
return false;
if (a.dynamic && b.dynamic)
return a.dynamicTypeName == b.dynamicTypeName;
if (a.dynamic || b.dynamic)
return false;
return a.gameObject == b.gameObject;
}
public static bool operator !=(TestComponent a, TestComponent b)
{
return !(a == b);
}
#endregion
#region Static helpers
public static TestComponent CreateDynamicTest(Type type)
{
var go = CreateTest(type.Name);
go.hideFlags |= HideFlags.DontSave;
go.SetActive(false);
var tc = go.GetComponent<TestComponent>();
tc.dynamic = true;
tc.dynamicTypeName = type.AssemblyQualifiedName;
#if !UNITY_METRO
foreach (var typeAttribute in type.GetCustomAttributes(false))
{
if (typeAttribute is IntegrationTest.TimeoutAttribute)
tc.timeout = (typeAttribute as IntegrationTest.TimeoutAttribute).timeout;
else if (typeAttribute is IntegrationTest.IgnoreAttribute)
tc.ignored = true;
else if (typeAttribute is IntegrationTest.SucceedWithAssertions)
tc.succeedAfterAllAssertionsAreExecuted = true;
else if (typeAttribute is IntegrationTest.ExcludePlatformAttribute)
tc.platformsToIgnore = (typeAttribute as IntegrationTest.ExcludePlatformAttribute).platformsToExclude;
else if (typeAttribute is IntegrationTest.ExpectExceptions)
{
var attribute = (typeAttribute as IntegrationTest.ExpectExceptions);
tc.expectException = true;
tc.expectedExceptionList = string.Join(",", attribute.exceptionTypeNames);
tc.succeedWhenExceptionIsThrown = attribute.succeedOnException;
}
}
go.AddComponent(type);
#endif // if !UNITY_METRO
return tc;
}
public static GameObject CreateTest()
{
return CreateTest("New Test");
}
private static GameObject CreateTest(string name)
{
var go = new GameObject(name);
go.AddComponent<TestComponent>();
#if UNITY_EDITOR
Undo.RegisterCreatedObjectUndo(go, "Created test");
#endif //UNITY_EDITOR
return go;
}
public static List<TestComponent> FindAllTestsOnScene()
{
var tests = Resources.FindObjectsOfTypeAll (typeof(TestComponent)).Cast<TestComponent> ();
#if UNITY_EDITOR
tests = tests.Where( t => {var p = PrefabUtility.GetPrefabType(t); return p != PrefabType.Prefab && p != PrefabType.ModelPrefab;} );
#endif
return tests.ToList ();
}
public static List<TestComponent> FindAllTopTestsOnScene()
{
return FindAllTestsOnScene().Where(component => component.gameObject.transform.parent == null).ToList();
}
public static List<TestComponent> FindAllDynamicTestsOnScene()
{
return FindAllTestsOnScene().Where(t => t.dynamic).ToList();
}
public static void DestroyAllDynamicTests()
{
foreach (var dynamicTestComponent in FindAllDynamicTestsOnScene())
DestroyImmediate(dynamicTestComponent.gameObject);
}
public static void DisableAllTests()
{
foreach (var t in FindAllTestsOnScene()) t.EnableTest(false);
}
public static bool AnyTestsOnScene()
{
return FindAllTestsOnScene().Any();
}
public static bool AnyDynamicTestForCurrentScene()
{
#if UNITY_EDITOR
return TestComponent.GetTypesWithHelpAttribute(EditorApplication.currentScene).Any();
#else
return TestComponent.GetTypesWithHelpAttribute(Application.loadedLevelName).Any();
#endif
}
#endregion
private sealed class NullTestComponentImpl : ITestComponent
{
public int CompareTo(ITestComponent other)
{
if (other == this) return 0;
return -1;
}
public void EnableTest(bool enable)
{
}
public bool IsTestGroup()
{
throw new NotImplementedException();
}
public GameObject gameObject { get; private set; }
public string Name { get { return ""; } }
public ITestComponent GetTestGroup()
{
return null;
}
public bool IsExceptionExpected(string exceptionType)
{
throw new NotImplementedException();
}
public bool ShouldSucceedOnException()
{
throw new NotImplementedException();
}
public double GetTimeout()
{
throw new NotImplementedException();
}
public bool IsIgnored()
{
throw new NotImplementedException();
}
public bool ShouldSucceedOnAssertions()
{
throw new NotImplementedException();
}
public bool IsExludedOnThisPlatform()
{
throw new NotImplementedException();
}
}
public static IEnumerable<Type> GetTypesWithHelpAttribute(string sceneName)
{
#if !UNITY_METRO
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type[] types = null;
try
{
types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
Debug.LogError("Failed to load types from: " + assembly.FullName);
foreach (Exception loadEx in ex.LoaderExceptions)
Debug.LogException(loadEx);
}
if (types == null)
continue;
foreach (Type type in types)
{
var attributes = type.GetCustomAttributes(typeof(IntegrationTest.DynamicTestAttribute), true);
if (attributes.Length == 1)
{
var a = attributes.Single() as IntegrationTest.DynamicTestAttribute;
if (a.IncludeOnScene(sceneName)) yield return type;
}
}
}
#else // if !UNITY_METRO
yield break;
#endif // if !UNITY_METRO
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using NUnit.Framework;
using Spring.Core;
#endregion
namespace Spring.Objects.Support
{
/// <summary>
/// Unit tests for the MethodInvoker class.
/// </summary>
/// <author>Rick Evans</author>
[TestFixture]
public sealed class MethodInvokerTests
{
[Test]
public void Instantiation()
{
MethodInvoker vkr = new MethodInvoker();
Assert.IsNotNull(vkr.Arguments);
}
[Test]
public void SettingNamedArgumentsToNullJustClearsOutAnyNamedArguments()
{
MethodInvoker vkr = new MethodInvoker();
vkr.AddNamedArgument("age", 10);
vkr.NamedArguments = null;
Assert.IsNotNull(vkr.NamedArguments);
Assert.AreEqual(0, vkr.NamedArguments.Count);
}
[Test]
[ExpectedException(typeof (ArgumentException), ExpectedMessage="One of either the 'TargetType' or 'TargetObject' properties is required.")]
public void PrepareWithOnlyTargetMethodSet()
{
MethodInvoker vkr = new MethodInvoker();
vkr.TargetMethod = "Foo";
vkr.Prepare();
}
[Test]
public void ArgumentsProperty()
{
MethodInvoker vkr = new MethodInvoker();
vkr.Arguments = null;
Assert.IsNotNull(vkr.Arguments); // should always be the empty object array, never null
Assert.AreEqual(0, vkr.Arguments.Length);
vkr.Arguments = new string[] {"Chank Pop"};
Assert.AreEqual(1, vkr.Arguments.Length);
}
[Test]
public void InvokeWithStaticMethod()
{
MethodInvoker mi = new MethodInvoker();
mi.TargetType = typeof(Int32);
mi.TargetMethod = "Parse";
mi.Arguments = new object[] { "27" };
mi.Prepare();
object actual = mi.Invoke();
Assert.IsNotNull(actual);
Assert.AreEqual(typeof(int), actual.GetType());
Assert.AreEqual(27, (int)actual);
}
[Test]
public void InvokeWithGenericStaticMethod()
{
MethodInvoker mi = new MethodInvoker();
mi.TargetType = typeof(Activator);
mi.TargetMethod = "CreateInstance<Spring.Objects.TestObject>";
mi.Prepare();
object actual = mi.Invoke();
Assert.IsNotNull(actual);
Assert.AreEqual(typeof(TestObject), actual.GetType());
}
[Test]
public void InvokeWithOKArguments()
{
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "GrowOlder";
vkr.Arguments = new object[] {10};
vkr.Prepare();
object actual = vkr.Invoke();
Assert.AreEqual(98, actual);
}
[Test]
public void InvokeWithOKArgumentsAndMixedCaseMethodName()
{
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "growolder";
vkr.Arguments = new object[] {10};
vkr.Prepare();
object actual = vkr.Invoke();
Assert.AreEqual(98, actual);
}
[Test]
public void InvokeWithNamedArgument()
{
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "growolder";
vkr.AddNamedArgument("years", 10);
vkr.Prepare();
object actual = vkr.Invoke();
Assert.AreEqual(98, actual);
}
[Test]
public void InvokeWithMixOfNamedAndPlainVanillaArguments()
{
int maximumAge = 95;
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "GrowOlderUntilMaximumAgeReached";
vkr.AddNamedArgument("years", 10);
vkr.Arguments = new object[] {maximumAge};
vkr.Prepare();
object actual = vkr.Invoke();
Assert.AreEqual(maximumAge, actual);
}
[Test]
public void InvokeWithMixOfNamedAndPlainVanillaArgumentsOfDifferingTypes()
{
int maximumAge = 95;
string expectedStatus = "Old Age Pensioner";
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "GrowOlderUntilMaximumAgeReachedAndSetStatusName";
vkr.AddNamedArgument("years", 10);
vkr.AddNamedArgument("status", expectedStatus);
vkr.Arguments = new object[] {maximumAge};
vkr.Prepare();
object actual = vkr.Invoke();
Assert.AreEqual(maximumAge, actual);
Assert.AreEqual(expectedStatus, foo.Status);
}
[Test]
[ExpectedException(
typeof (ArgumentException),
ExpectedMessage = "The named argument 'southpaw' could not be found on the 'GrowOlder' method of class [Spring.Objects.Support.MethodInvokerTests+Foo].")]
public void InvokeWithNamedArgumentThatDoesNotExist()
{
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "growolder";
vkr.AddNamedArgument("southpaw", 10);
vkr.Prepare();
object actual = vkr.Invoke();
Assert.AreEqual(98, actual);
}
/// <summary>
/// Tests CLS case insensitivity compliance...
/// </summary>
[Test]
public void InvokeWithWeIRdLyCasedNamedArgument()
{
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "gROwOldeR";
vkr.AddNamedArgument("YEarS", 10);
vkr.Prepare();
object actual = vkr.Invoke();
Assert.AreEqual(98, actual);
}
[Test]
[ExpectedException(typeof (MethodInvocationException), ExpectedMessage="At least one of the arguments passed to this MethodInvoker was incompatible with the signature of the invoked method.")]
public void InvokeWithArgumentOfWrongType()
{
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "growolder";
vkr.AddNamedArgument("years", "Bingo");
vkr.Prepare();
vkr.Invoke();
}
[Test]
public void NamedArgumentsOverwriteEachOther()
{
Foo foo = new Foo();
foo.Age = 88;
MethodInvoker vkr = new MethodInvoker();
vkr.TargetObject = foo;
vkr.TargetMethod = "growolder";
vkr.AddNamedArgument("years", 10);
// this second setting must overwrite the first...
vkr.AddNamedArgument("years", 200);
vkr.Prepare();
object actual = vkr.Invoke();
Assert.IsFalse(98.Equals(actual), "The first named argument setter is sticking; must allow itslf to be overwritten.");
Assert.AreEqual(288, actual, "The second named argument was not applied (it must be).");
}
[Test]
public void PreparedArgumentsIsNeverNull()
{
MyMethodInvoker vkr = new MyMethodInvoker();
Assert.IsNotNull(vkr.GetPreparedArguments(),
"PreparedArguments is null even before Prepare() is called; must NEVER be null.");
vkr.NullOutPreparedArguments();
Assert.IsNotNull(vkr.GetPreparedArguments(),
"PreparedArguments should revert to the empty object[] when set to null; must NEVER be null.");
}
#region Inner Class : Foo
private sealed class Foo
{
public Foo()
{
Age = 0;
Status = "Baby";
}
public int GrowOlder()
{
return GrowOlder(1);
}
public int GrowOlder(int years)
{
_age += years;
return _age;
}
public int GrowOlderUntilMaximumAgeReached(int years, int maximumAge)
{
_age += years;
if (_age > maximumAge)
{
_age = maximumAge;
}
return _age;
}
public int GrowOlderUntilMaximumAgeReachedAndSetStatusName(
int years, int maximumAge, string status)
{
Status = status;
return GrowOlderUntilMaximumAgeReached(years, maximumAge);
}
private int _age;
private string _status;
public int Age
{
get { return _age; }
set { _age = value; }
}
public string Status
{
get { return _status; }
set { _status = value; }
}
}
#endregion
#region Inner Class : MyMethodInvoker
private sealed class MyMethodInvoker : MethodInvoker
{
public MyMethodInvoker()
{
}
public void NullOutPreparedArguments()
{
PreparedArguments = null;
}
public object[] GetPreparedArguments()
{
return PreparedArguments;
}
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using System.Linq;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Verify.V2.Service
{
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Create a new Webhook for the Service
/// </summary>
public class CreateWebhookOptions : IOptions<WebhookResource>
{
/// <summary>
/// Service Sid.
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The string that you assigned to describe the webhook
/// </summary>
public string FriendlyName { get; }
/// <summary>
/// The array of events that this Webhook is subscribed to.
/// </summary>
public List<string> EventTypes { get; }
/// <summary>
/// The URL associated with this Webhook.
/// </summary>
public string WebhookUrl { get; }
/// <summary>
/// The webhook status
/// </summary>
public WebhookResource.StatusEnum Status { get; set; }
/// <summary>
/// The webhook version
/// </summary>
public WebhookResource.VersionEnum Version { get; set; }
/// <summary>
/// Construct a new CreateWebhookOptions
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="friendlyName"> The string that you assigned to describe the webhook </param>
/// <param name="eventTypes"> The array of events that this Webhook is subscribed to. </param>
/// <param name="webhookUrl"> The URL associated with this Webhook. </param>
public CreateWebhookOptions(string pathServiceSid, string friendlyName, List<string> eventTypes, string webhookUrl)
{
PathServiceSid = pathServiceSid;
FriendlyName = friendlyName;
EventTypes = eventTypes;
WebhookUrl = webhookUrl;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (EventTypes != null)
{
p.AddRange(EventTypes.Select(prop => new KeyValuePair<string, string>("EventTypes", prop)));
}
if (WebhookUrl != null)
{
p.Add(new KeyValuePair<string, string>("WebhookUrl", WebhookUrl));
}
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (Version != null)
{
p.Add(new KeyValuePair<string, string>("Version", Version.ToString()));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// UpdateWebhookOptions
/// </summary>
public class UpdateWebhookOptions : IOptions<WebhookResource>
{
/// <summary>
/// Service Sid.
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// The string that you assigned to describe the webhook
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The array of events that this Webhook is subscribed to.
/// </summary>
public List<string> EventTypes { get; set; }
/// <summary>
/// The URL associated with this Webhook.
/// </summary>
public string WebhookUrl { get; set; }
/// <summary>
/// The webhook status
/// </summary>
public WebhookResource.StatusEnum Status { get; set; }
/// <summary>
/// The webhook version
/// </summary>
public WebhookResource.VersionEnum Version { get; set; }
/// <summary>
/// Construct a new UpdateWebhookOptions
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public UpdateWebhookOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
EventTypes = new List<string>();
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (EventTypes != null)
{
p.AddRange(EventTypes.Select(prop => new KeyValuePair<string, string>("EventTypes", prop)));
}
if (WebhookUrl != null)
{
p.Add(new KeyValuePair<string, string>("WebhookUrl", WebhookUrl));
}
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (Version != null)
{
p.Add(new KeyValuePair<string, string>("Version", Version.ToString()));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Delete a specific Webhook.
/// </summary>
public class DeleteWebhookOptions : IOptions<WebhookResource>
{
/// <summary>
/// Service Sid.
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique string that identifies the resource to delete
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteWebhookOptions
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathSid"> The unique string that identifies the resource to delete </param>
public DeleteWebhookOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Fetch a specific Webhook.
/// </summary>
public class FetchWebhookOptions : IOptions<WebhookResource>
{
/// <summary>
/// Service Sid.
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The unique string that identifies the resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchWebhookOptions
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathSid"> The unique string that identifies the resource to fetch </param>
public FetchWebhookOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// Retrieve a list of all Webhooks for a Service.
/// </summary>
public class ReadWebhookOptions : ReadOptions<WebhookResource>
{
/// <summary>
/// Service Sid.
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// Construct a new ReadWebhookOptions
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
public ReadWebhookOptions(string pathServiceSid)
{
PathServiceSid = pathServiceSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
}
| |
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
using Com.Adobe.Xmp;
using Com.Adobe.Xmp.Impl.Xpath;
using Com.Adobe.Xmp.Options;
using Com.Adobe.Xmp.Properties;
using Sharpen;
namespace Com.Adobe.Xmp.Impl
{
/// <summary>
/// Implementation for
/// <see cref="Com.Adobe.Xmp.XMPMeta"/>
/// .
/// </summary>
/// <since>17.02.2006</since>
public class XMPMetaImpl : XMPMeta, XMPConst
{
/// <summary>Property values are Strings by default</summary>
private const int ValueString = 0;
private const int ValueBoolean = 1;
private const int ValueInteger = 2;
private const int ValueLong = 3;
private const int ValueDouble = 4;
private const int ValueDate = 5;
private const int ValueCalendar = 6;
private const int ValueBase64 = 7;
/// <summary>root of the metadata tree</summary>
private XMPNode tree;
/// <summary>the xpacket processing instructions content</summary>
private string packetHeader = null;
/// <summary>Constructor for an empty metadata object.</summary>
public XMPMetaImpl()
{
// create root node
tree = new XMPNode(null, null, null);
}
/// <summary>Constructor for a cloned metadata tree.</summary>
/// <param name="tree">
/// an prefilled metadata tree which fulfills all
/// <code>XMPNode</code> contracts.
/// </param>
public XMPMetaImpl(XMPNode tree)
{
this.tree = tree;
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.AppendArrayItem(string, string, Com.Adobe.Xmp.Options.PropertyOptions, string, Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void AppendArrayItem(string schemaNS, string arrayName, PropertyOptions arrayOptions, string itemValue, PropertyOptions itemOptions)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
if (arrayOptions == null)
{
arrayOptions = new PropertyOptions();
}
if (!arrayOptions.IsOnlyArrayOptions())
{
throw new XMPException("Only array form flags allowed for arrayOptions", XMPErrorConstants.Badoptions);
}
// Check if array options are set correctly.
arrayOptions = XMPNodeUtils.VerifySetOptions(arrayOptions, null);
// Locate or create the array. If it already exists, make sure the array
// form from the options
// parameter is compatible with the current state.
XMPPath arrayPath = XMPPathParser.ExpandXPath(schemaNS, arrayName);
// Just lookup, don't try to create.
XMPNode arrayNode = XMPNodeUtils.FindNode(tree, arrayPath, false, null);
if (arrayNode != null)
{
// The array exists, make sure the form is compatible. Zero
// arrayForm means take what exists.
if (!arrayNode.GetOptions().IsArray())
{
throw new XMPException("The named property is not an array", XMPErrorConstants.Badxpath);
}
}
else
{
// if (arrayOptions != null && !arrayOptions.equalArrayTypes(arrayNode.getOptions()))
// {
// throw new XMPException("Mismatch of existing and specified array form", BADOPTIONS);
// }
// The array does not exist, try to create it.
if (arrayOptions.IsArray())
{
arrayNode = XMPNodeUtils.FindNode(tree, arrayPath, true, arrayOptions);
if (arrayNode == null)
{
throw new XMPException("Failure creating array node", XMPErrorConstants.Badxpath);
}
}
else
{
// array options missing
throw new XMPException("Explicit arrayOptions required to create new array", XMPErrorConstants.Badoptions);
}
}
DoSetArrayItem(arrayNode, XMPConstConstants.ArrayLastItem, itemValue, itemOptions, true);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.AppendArrayItem(string, string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void AppendArrayItem(string schemaNS, string arrayName, string itemValue)
{
AppendArrayItem(schemaNS, arrayName, null, itemValue, null);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.CountArrayItems(string, string)"/>
public virtual int CountArrayItems(string schemaNS, string arrayName)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
XMPPath arrayPath = XMPPathParser.ExpandXPath(schemaNS, arrayName);
XMPNode arrayNode = XMPNodeUtils.FindNode(tree, arrayPath, false, null);
if (arrayNode == null)
{
return 0;
}
if (arrayNode.GetOptions().IsArray())
{
return arrayNode.GetChildrenLength();
}
else
{
throw new XMPException("The named property is not an array", XMPErrorConstants.Badxpath);
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DeleteArrayItem(string, string, int)"/>
public virtual void DeleteArrayItem(string schemaNS, string arrayName, int itemIndex)
{
try
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
string itemPath = XMPPathFactory.ComposeArrayItemPath(arrayName, itemIndex);
DeleteProperty(schemaNS, itemPath);
}
catch (XMPException)
{
}
}
// EMPTY, exceptions are ignored within delete
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DeleteProperty(string, string)"/>
public virtual void DeleteProperty(string schemaNS, string propName)
{
try
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
XMPPath expPath = XMPPathParser.ExpandXPath(schemaNS, propName);
XMPNode propNode = XMPNodeUtils.FindNode(tree, expPath, false, null);
if (propNode != null)
{
XMPNodeUtils.DeleteNode(propNode);
}
}
catch (XMPException)
{
}
}
// EMPTY, exceptions are ignored within delete
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DeleteQualifier(string, string, string, string)"/>
public virtual void DeleteQualifier(string schemaNS, string propName, string qualNS, string qualName)
{
try
{
// Note: qualNS and qualName are checked inside composeQualfierPath
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
string qualPath = propName + XMPPathFactory.ComposeQualifierPath(qualNS, qualName);
DeleteProperty(schemaNS, qualPath);
}
catch (XMPException)
{
}
}
// EMPTY, exceptions within delete are ignored
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DeleteStructField(string, string, string, string)"/>
public virtual void DeleteStructField(string schemaNS, string structName, string fieldNS, string fieldName)
{
try
{
// fieldNS and fieldName are checked inside composeStructFieldPath
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertStructName(structName);
string fieldPath = structName + XMPPathFactory.ComposeStructFieldPath(fieldNS, fieldName);
DeleteProperty(schemaNS, fieldPath);
}
catch (XMPException)
{
}
}
// EMPTY, exceptions within delete are ignored
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DoesPropertyExist(string, string)"/>
public virtual bool DoesPropertyExist(string schemaNS, string propName)
{
try
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
XMPPath expPath = XMPPathParser.ExpandXPath(schemaNS, propName);
XMPNode propNode = XMPNodeUtils.FindNode(tree, expPath, false, null);
return propNode != null;
}
catch (XMPException)
{
return false;
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DoesArrayItemExist(string, string, int)"/>
public virtual bool DoesArrayItemExist(string schemaNS, string arrayName, int itemIndex)
{
try
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
string path = XMPPathFactory.ComposeArrayItemPath(arrayName, itemIndex);
return DoesPropertyExist(schemaNS, path);
}
catch (XMPException)
{
return false;
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DoesStructFieldExist(string, string, string, string)"/>
public virtual bool DoesStructFieldExist(string schemaNS, string structName, string fieldNS, string fieldName)
{
try
{
// fieldNS and fieldName are checked inside composeStructFieldPath()
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertStructName(structName);
string path = XMPPathFactory.ComposeStructFieldPath(fieldNS, fieldName);
return DoesPropertyExist(schemaNS, structName + path);
}
catch (XMPException)
{
return false;
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DoesQualifierExist(string, string, string, string)"/>
public virtual bool DoesQualifierExist(string schemaNS, string propName, string qualNS, string qualName)
{
try
{
// qualNS and qualName are checked inside composeQualifierPath()
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
string path = XMPPathFactory.ComposeQualifierPath(qualNS, qualName);
return DoesPropertyExist(schemaNS, propName + path);
}
catch (XMPException)
{
return false;
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetArrayItem(string, string, int)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual XMPProperty GetArrayItem(string schemaNS, string arrayName, int itemIndex)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
string itemPath = XMPPathFactory.ComposeArrayItemPath(arrayName, itemIndex);
return GetProperty(schemaNS, itemPath);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetLocalizedText(string, string, string, string)"/>
public virtual XMPProperty GetLocalizedText(string schemaNS, string altTextName, string genericLang, string specificLang)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(altTextName);
ParameterAsserts.AssertSpecificLang(specificLang);
genericLang = genericLang != null ? Utils.NormalizeLangValue(genericLang) : null;
specificLang = Utils.NormalizeLangValue(specificLang);
XMPPath arrayPath = XMPPathParser.ExpandXPath(schemaNS, altTextName);
XMPNode arrayNode = XMPNodeUtils.FindNode(tree, arrayPath, false, null);
if (arrayNode == null)
{
return null;
}
object[] result = XMPNodeUtils.ChooseLocalizedText(arrayNode, genericLang, specificLang);
int match = ((int)result[0]).IntValue();
XMPNode itemNode = (XMPNode)result[1];
if (match != XMPNodeUtils.CltNoValues)
{
return new _XMPProperty_407(itemNode);
}
else
{
return null;
}
}
private sealed class _XMPProperty_407 : XMPProperty
{
public _XMPProperty_407(XMPNode itemNode)
{
this.itemNode = itemNode;
}
public string GetValue()
{
return itemNode.GetValue();
}
public PropertyOptions GetOptions()
{
return itemNode.GetOptions();
}
public string GetLanguage()
{
return itemNode.GetQualifier(1).GetValue();
}
public override string ToString()
{
return itemNode.GetValue().ToString();
}
private readonly XMPNode itemNode;
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetLocalizedText(string, string, string, string, string, Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetLocalizedText(string schemaNS, string altTextName, string genericLang, string specificLang, string itemValue, PropertyOptions options)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(altTextName);
ParameterAsserts.AssertSpecificLang(specificLang);
genericLang = genericLang != null ? Utils.NormalizeLangValue(genericLang) : null;
specificLang = Utils.NormalizeLangValue(specificLang);
XMPPath arrayPath = XMPPathParser.ExpandXPath(schemaNS, altTextName);
// Find the array node and set the options if it was just created.
XMPNode arrayNode = XMPNodeUtils.FindNode(tree, arrayPath, true, new PropertyOptions(PropertyOptions.Array | PropertyOptions.ArrayOrdered | PropertyOptions.ArrayAlternate | PropertyOptions.ArrayAltText));
if (arrayNode == null)
{
throw new XMPException("Failed to find or create array node", XMPErrorConstants.Badxpath);
}
else
{
if (!arrayNode.GetOptions().IsArrayAltText())
{
if (!arrayNode.HasChildren() && arrayNode.GetOptions().IsArrayAlternate())
{
arrayNode.GetOptions().SetArrayAltText(true);
}
else
{
throw new XMPException("Specified property is no alt-text array", XMPErrorConstants.Badxpath);
}
}
}
// Make sure the x-default item, if any, is first.
bool haveXDefault = false;
XMPNode xdItem = null;
for (Sharpen.Iterator it = arrayNode.IterateChildren(); it.HasNext(); )
{
XMPNode currItem = (XMPNode)it.Next();
if (!currItem.HasQualifier() || !XMPConstConstants.XmlLang.Equals(currItem.GetQualifier(1).GetName()))
{
throw new XMPException("Language qualifier must be first", XMPErrorConstants.Badxpath);
}
else
{
if (XMPConstConstants.XDefault.Equals(currItem.GetQualifier(1).GetValue()))
{
xdItem = currItem;
haveXDefault = true;
break;
}
}
}
// Moves x-default to the beginning of the array
if (xdItem != null && arrayNode.GetChildrenLength() > 1)
{
arrayNode.RemoveChild(xdItem);
arrayNode.AddChild(1, xdItem);
}
// Find the appropriate item.
// chooseLocalizedText will make sure the array is a language
// alternative.
object[] result = XMPNodeUtils.ChooseLocalizedText(arrayNode, genericLang, specificLang);
int match = ((int)result[0]).IntValue();
XMPNode itemNode = (XMPNode)result[1];
bool specificXDefault = XMPConstConstants.XDefault.Equals(specificLang);
switch (match)
{
case XMPNodeUtils.CltNoValues:
{
// Create the array items for the specificLang and x-default, with
// x-default first.
XMPNodeUtils.AppendLangItem(arrayNode, XMPConstConstants.XDefault, itemValue);
haveXDefault = true;
if (!specificXDefault)
{
XMPNodeUtils.AppendLangItem(arrayNode, specificLang, itemValue);
}
break;
}
case XMPNodeUtils.CltSpecificMatch:
{
if (!specificXDefault)
{
// Update the specific item, update x-default if it matches the
// old value.
if (haveXDefault && xdItem != itemNode && xdItem != null && xdItem.GetValue().Equals(itemNode.GetValue()))
{
xdItem.SetValue(itemValue);
}
// ! Do this after the x-default check!
itemNode.SetValue(itemValue);
}
else
{
// Update all items whose values match the old x-default value.
System.Diagnostics.Debug.Assert(haveXDefault && xdItem == itemNode);
for (Sharpen.Iterator it_1 = arrayNode.IterateChildren(); it_1.HasNext(); )
{
XMPNode currItem = (XMPNode)it_1.Next();
if (currItem == xdItem || !currItem.GetValue().Equals(xdItem != null ? xdItem.GetValue() : null))
{
continue;
}
currItem.SetValue(itemValue);
}
// And finally do the x-default item.
if (xdItem != null)
{
xdItem.SetValue(itemValue);
}
}
break;
}
case XMPNodeUtils.CltSingleGeneric:
{
// Update the generic item, update x-default if it matches the old
// value.
if (haveXDefault && xdItem != itemNode && xdItem != null && xdItem.GetValue().Equals(itemNode.GetValue()))
{
xdItem.SetValue(itemValue);
}
itemNode.SetValue(itemValue);
// ! Do this after
// the x-default
// check!
break;
}
case XMPNodeUtils.CltMultipleGeneric:
{
// Create the specific language, ignore x-default.
XMPNodeUtils.AppendLangItem(arrayNode, specificLang, itemValue);
if (specificXDefault)
{
haveXDefault = true;
}
break;
}
case XMPNodeUtils.CltXdefault:
{
// Create the specific language, update x-default if it was the only
// item.
if (xdItem != null && arrayNode.GetChildrenLength() == 1)
{
xdItem.SetValue(itemValue);
}
XMPNodeUtils.AppendLangItem(arrayNode, specificLang, itemValue);
break;
}
case XMPNodeUtils.CltFirstItem:
{
// Create the specific language, don't add an x-default item.
XMPNodeUtils.AppendLangItem(arrayNode, specificLang, itemValue);
if (specificXDefault)
{
haveXDefault = true;
}
break;
}
default:
{
// does not happen under normal circumstances
throw new XMPException("Unexpected result from ChooseLocalizedText", XMPErrorConstants.Internalfailure);
}
}
// Add an x-default at the front if needed.
if (!haveXDefault && arrayNode.GetChildrenLength() == 1)
{
XMPNodeUtils.AppendLangItem(arrayNode, XMPConstConstants.XDefault, itemValue);
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetLocalizedText(string, string, string, string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetLocalizedText(string schemaNS, string altTextName, string genericLang, string specificLang, string itemValue)
{
SetLocalizedText(schemaNS, altTextName, genericLang, specificLang, itemValue, null);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetProperty(string, string)"/>
public virtual XMPProperty GetProperty(string schemaNS, string propName)
{
return GetProperty(schemaNS, propName, ValueString);
}
/// <summary>Returns a property, but the result value can be requested.</summary>
/// <remarks>
/// Returns a property, but the result value can be requested. It can be one
/// of
/// <see cref="ValueString"/>
/// ,
/// <see cref="ValueBoolean"/>
/// ,
/// <see cref="ValueInteger"/>
/// ,
/// <see cref="ValueLong"/>
/// ,
/// <see cref="ValueDouble"/>
/// ,
/// <see cref="ValueDate"/>
/// ,
/// <see cref="ValueCalendar"/>
/// ,
/// <see cref="ValueBase64"/>
/// .
/// </remarks>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetProperty(string, string)"/>
/// <param name="schemaNS">a schema namespace</param>
/// <param name="propName">a property name or path</param>
/// <param name="valueType">the type of the value, see VALUE_...</param>
/// <returns>Returns an <code>XMPProperty</code></returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">Collects any exception that occurs.</exception>
protected internal virtual XMPProperty GetProperty(string schemaNS, string propName, int valueType)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
XMPPath expPath = XMPPathParser.ExpandXPath(schemaNS, propName);
XMPNode propNode = XMPNodeUtils.FindNode(tree, expPath, false, null);
if (propNode != null)
{
if (valueType != ValueString && propNode.GetOptions().IsCompositeProperty())
{
throw new XMPException("Property must be simple when a value type is requested", XMPErrorConstants.Badxpath);
}
object value = EvaluateNodeValue(valueType, propNode);
return new _XMPProperty_682(value, propNode);
}
else
{
return null;
}
}
private sealed class _XMPProperty_682 : XMPProperty
{
public _XMPProperty_682(object value, XMPNode propNode)
{
this.value = value;
this.propNode = propNode;
}
public string GetValue()
{
return value != null ? value.ToString() : null;
}
public PropertyOptions GetOptions()
{
return propNode.GetOptions();
}
public string GetLanguage()
{
return null;
}
public override string ToString()
{
return value.ToString();
}
private readonly object value;
private readonly XMPNode propNode;
}
/// <summary>Returns a property, but the result value can be requested.</summary>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetProperty(string, string)"/>
/// <param name="schemaNS">a schema namespace</param>
/// <param name="propName">a property name or path</param>
/// <param name="valueType">the type of the value, see VALUE_...</param>
/// <returns>
/// Returns the node value as an object according to the
/// <code>valueType</code>.
/// </returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">Collects any exception that occurs.</exception>
protected internal virtual object GetPropertyObject(string schemaNS, string propName, int valueType)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
XMPPath expPath = XMPPathParser.ExpandXPath(schemaNS, propName);
XMPNode propNode = XMPNodeUtils.FindNode(tree, expPath, false, null);
if (propNode != null)
{
if (valueType != ValueString && propNode.GetOptions().IsCompositeProperty())
{
throw new XMPException("Property must be simple when a value type is requested", XMPErrorConstants.Badxpath);
}
return EvaluateNodeValue(valueType, propNode);
}
else
{
return null;
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPropertyBoolean(string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual bool GetPropertyBoolean(string schemaNS, string propName)
{
return (bool)GetPropertyObject(schemaNS, propName, ValueBoolean);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyBoolean(string, string, bool, Com.Adobe.Xmp.Options.PropertyOptions)"/>
public virtual void SetPropertyBoolean(string schemaNS, string propName, bool propValue, PropertyOptions options)
{
SetProperty(schemaNS, propName, propValue ? XMPConstConstants.Truestr : XMPConstConstants.Falsestr, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyBoolean(string, string, bool)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyBoolean(string schemaNS, string propName, bool propValue)
{
SetProperty(schemaNS, propName, propValue ? XMPConstConstants.Truestr : XMPConstConstants.Falsestr, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPropertyInteger(string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual int GetPropertyInteger(string schemaNS, string propName)
{
return (int)GetPropertyObject(schemaNS, propName, ValueInteger);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyInteger(string, string, int, Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyInteger(string schemaNS, string propName, int propValue, PropertyOptions options)
{
SetProperty(schemaNS, propName, propValue, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyInteger(string, string, int)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyInteger(string schemaNS, string propName, int propValue)
{
SetProperty(schemaNS, propName, propValue, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPropertyLong(string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual long GetPropertyLong(string schemaNS, string propName)
{
return (long)GetPropertyObject(schemaNS, propName, ValueLong);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyLong(string, string, long, Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyLong(string schemaNS, string propName, long propValue, PropertyOptions options)
{
SetProperty(schemaNS, propName, propValue, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyLong(string, string, long)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyLong(string schemaNS, string propName, long propValue)
{
SetProperty(schemaNS, propName, propValue, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPropertyDouble(string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual double GetPropertyDouble(string schemaNS, string propName)
{
return (double)GetPropertyObject(schemaNS, propName, ValueDouble);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyDouble(string, string, double, Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyDouble(string schemaNS, string propName, double propValue, PropertyOptions options)
{
SetProperty(schemaNS, propName, propValue, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyDouble(string, string, double)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyDouble(string schemaNS, string propName, double propValue)
{
SetProperty(schemaNS, propName, propValue, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPropertyDate(string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual XMPDateTime GetPropertyDate(string schemaNS, string propName)
{
return (XMPDateTime)GetPropertyObject(schemaNS, propName, ValueDate);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyDate(string, string, Com.Adobe.Xmp.XMPDateTime, Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyDate(string schemaNS, string propName, XMPDateTime propValue, PropertyOptions options)
{
SetProperty(schemaNS, propName, propValue, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyDate(string, string, Com.Adobe.Xmp.XMPDateTime)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyDate(string schemaNS, string propName, XMPDateTime propValue)
{
SetProperty(schemaNS, propName, propValue, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPropertyCalendar(string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual Sharpen.Calendar GetPropertyCalendar(string schemaNS, string propName)
{
return (Sharpen.Calendar)GetPropertyObject(schemaNS, propName, ValueCalendar);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyCalendar(string, string, Sharpen.Calendar, Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyCalendar(string schemaNS, string propName, Sharpen.Calendar propValue, PropertyOptions options)
{
SetProperty(schemaNS, propName, propValue, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyCalendar(string, string, Sharpen.Calendar)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyCalendar(string schemaNS, string propName, Sharpen.Calendar propValue)
{
SetProperty(schemaNS, propName, propValue, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPropertyBase64(string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual sbyte[] GetPropertyBase64(string schemaNS, string propName)
{
return (sbyte[])GetPropertyObject(schemaNS, propName, ValueBase64);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPropertyString(string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual string GetPropertyString(string schemaNS, string propName)
{
return (string)GetPropertyObject(schemaNS, propName, ValueString);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyBase64(string, string, sbyte[], Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyBase64(string schemaNS, string propName, sbyte[] propValue, PropertyOptions options)
{
SetProperty(schemaNS, propName, propValue, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetPropertyBase64(string, string, sbyte[])"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetPropertyBase64(string schemaNS, string propName, sbyte[] propValue)
{
SetProperty(schemaNS, propName, propValue, null);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetQualifier(string, string, string, string)"/>
public virtual XMPProperty GetQualifier(string schemaNS, string propName, string qualNS, string qualName)
{
// qualNS and qualName are checked inside composeQualfierPath
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
string qualPath = propName + XMPPathFactory.ComposeQualifierPath(qualNS, qualName);
return GetProperty(schemaNS, qualPath);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetStructField(string, string, string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual XMPProperty GetStructField(string schemaNS, string structName, string fieldNS, string fieldName)
{
// fieldNS and fieldName are checked inside composeStructFieldPath
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertStructName(structName);
string fieldPath = structName + XMPPathFactory.ComposeStructFieldPath(fieldNS, fieldName);
return GetProperty(schemaNS, fieldPath);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.Iterator()"/>
public virtual XMPIterator Iterator()
{
return Iterator(null, null, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.Iterator(Com.Adobe.Xmp.Options.IteratorOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual XMPIterator Iterator(IteratorOptions options)
{
return Iterator(null, null, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.Iterator(string, string, Com.Adobe.Xmp.Options.IteratorOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual XMPIterator Iterator(string schemaNS, string propName, IteratorOptions options)
{
return new XMPIteratorImpl(this, schemaNS, propName, options);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetArrayItem(string, string, int, string, Com.Adobe.Xmp.Options.PropertyOptions)"/>
public virtual void SetArrayItem(string schemaNS, string arrayName, int itemIndex, string itemValue, PropertyOptions options)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
// Just lookup, don't try to create.
XMPPath arrayPath = XMPPathParser.ExpandXPath(schemaNS, arrayName);
XMPNode arrayNode = XMPNodeUtils.FindNode(tree, arrayPath, false, null);
if (arrayNode != null)
{
DoSetArrayItem(arrayNode, itemIndex, itemValue, options, false);
}
else
{
throw new XMPException("Specified array does not exist", XMPErrorConstants.Badxpath);
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetArrayItem(string, string, int, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetArrayItem(string schemaNS, string arrayName, int itemIndex, string itemValue)
{
SetArrayItem(schemaNS, arrayName, itemIndex, itemValue, null);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.InsertArrayItem(string, string, int, string, Com.Adobe.Xmp.Options.PropertyOptions)"/>
public virtual void InsertArrayItem(string schemaNS, string arrayName, int itemIndex, string itemValue, PropertyOptions options)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
// Just lookup, don't try to create.
XMPPath arrayPath = XMPPathParser.ExpandXPath(schemaNS, arrayName);
XMPNode arrayNode = XMPNodeUtils.FindNode(tree, arrayPath, false, null);
if (arrayNode != null)
{
DoSetArrayItem(arrayNode, itemIndex, itemValue, options, true);
}
else
{
throw new XMPException("Specified array does not exist", XMPErrorConstants.Badxpath);
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.InsertArrayItem(string, string, int, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void InsertArrayItem(string schemaNS, string arrayName, int itemIndex, string itemValue)
{
InsertArrayItem(schemaNS, arrayName, itemIndex, itemValue, null);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetProperty(string, string, object, Com.Adobe.Xmp.Options.PropertyOptions)"/>
public virtual void SetProperty(string schemaNS, string propName, object propValue, PropertyOptions options)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
options = XMPNodeUtils.VerifySetOptions(options, propValue);
XMPPath expPath = XMPPathParser.ExpandXPath(schemaNS, propName);
XMPNode propNode = XMPNodeUtils.FindNode(tree, expPath, true, options);
if (propNode != null)
{
SetNode(propNode, propValue, options, false);
}
else
{
throw new XMPException("Specified property does not exist", XMPErrorConstants.Badxpath);
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetProperty(string, string, object)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetProperty(string schemaNS, string propName, object propValue)
{
SetProperty(schemaNS, propName, propValue, null);
}
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetQualifier(string, string, string, string, string, Com.Adobe.Xmp.Options.PropertyOptions)"/>
public virtual void SetQualifier(string schemaNS, string propName, string qualNS, string qualName, string qualValue, PropertyOptions options)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertPropName(propName);
if (!DoesPropertyExist(schemaNS, propName))
{
throw new XMPException("Specified property does not exist!", XMPErrorConstants.Badxpath);
}
string qualPath = propName + XMPPathFactory.ComposeQualifierPath(qualNS, qualName);
SetProperty(schemaNS, qualPath, qualValue, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetQualifier(string, string, string, string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetQualifier(string schemaNS, string propName, string qualNS, string qualName, string qualValue)
{
SetQualifier(schemaNS, propName, qualNS, qualName, qualValue, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetStructField(string, string, string, string, string, Com.Adobe.Xmp.Options.PropertyOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetStructField(string schemaNS, string structName, string fieldNS, string fieldName, string fieldValue, PropertyOptions options)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertStructName(structName);
string fieldPath = structName + XMPPathFactory.ComposeStructFieldPath(fieldNS, fieldName);
SetProperty(schemaNS, fieldPath, fieldValue, options);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetStructField(string, string, string, string, string)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void SetStructField(string schemaNS, string structName, string fieldNS, string fieldName, string fieldValue)
{
SetStructField(schemaNS, structName, fieldNS, fieldName, fieldValue, null);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetObjectName()"/>
public virtual string GetObjectName()
{
return tree.GetName() != null ? tree.GetName() : string.Empty;
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.SetObjectName(string)"/>
public virtual void SetObjectName(string name)
{
tree.SetName(name);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.GetPacketHeader()"/>
public virtual string GetPacketHeader()
{
return packetHeader;
}
/// <summary>Sets the packetHeader attributes, only used by the parser.</summary>
/// <param name="packetHeader">the processing instruction content</param>
public virtual void SetPacketHeader(string packetHeader)
{
this.packetHeader = packetHeader;
}
/// <summary>Performs a deep clone of the XMPMeta-object</summary>
/// <seealso cref="object.Clone()"/>
public virtual object Clone()
{
XMPNode clonedTree = (XMPNode)tree.Clone();
return new Com.Adobe.Xmp.Impl.XMPMetaImpl(clonedTree);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.DumpObject()"/>
public virtual string DumpObject()
{
// renders tree recursively
return GetRoot().DumpNode(true);
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.Sort()"/>
public virtual void Sort()
{
this.tree.Sort();
}
/// <seealso cref="Com.Adobe.Xmp.XMPMeta.Normalize(Com.Adobe.Xmp.Options.ParseOptions)"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
public virtual void Normalize(ParseOptions options)
{
if (options == null)
{
options = new ParseOptions();
}
XMPNormalizer.Process(this, options);
}
/// <returns>Returns the root node of the XMP tree.</returns>
public virtual XMPNode GetRoot()
{
return tree;
}
// -------------------------------------------------------------------------------------
// private
/// <summary>Locate or create the item node and set the value.</summary>
/// <remarks>
/// Locate or create the item node and set the value. Note the index
/// parameter is one-based! The index can be in the range [1..size + 1] or
/// "last()", normalize it and check the insert flags. The order of the
/// normalization checks is important. If the array is empty we end up with
/// an index and location to set item size + 1.
/// </remarks>
/// <param name="arrayNode">an array node</param>
/// <param name="itemIndex">the index where to insert the item</param>
/// <param name="itemValue">the item value</param>
/// <param name="itemOptions">the options for the new item</param>
/// <param name="insert">insert oder overwrite at index position?</param>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
private void DoSetArrayItem(XMPNode arrayNode, int itemIndex, string itemValue, PropertyOptions itemOptions, bool insert)
{
XMPNode itemNode = new XMPNode(XMPConstConstants.ArrayItemName, null);
itemOptions = XMPNodeUtils.VerifySetOptions(itemOptions, itemValue);
// in insert mode the index after the last is allowed,
// even ARRAY_LAST_ITEM points to the index *after* the last.
int maxIndex = insert ? arrayNode.GetChildrenLength() + 1 : arrayNode.GetChildrenLength();
if (itemIndex == XMPConstConstants.ArrayLastItem)
{
itemIndex = maxIndex;
}
if (1 <= itemIndex && itemIndex <= maxIndex)
{
if (!insert)
{
arrayNode.RemoveChild(itemIndex);
}
arrayNode.AddChild(itemIndex, itemNode);
SetNode(itemNode, itemValue, itemOptions, false);
}
else
{
throw new XMPException("Array index out of bounds", XMPErrorConstants.Badindex);
}
}
/// <summary>
/// The internals for setProperty() and related calls, used after the node is
/// found or created.
/// </summary>
/// <param name="node">the newly created node</param>
/// <param name="value">the node value, can be <code>null</code></param>
/// <param name="newOptions">options for the new node, must not be <code>null</code>.</param>
/// <param name="deleteExisting">flag if the existing value is to be overwritten</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">thrown if options and value do not correspond</exception>
internal virtual void SetNode(XMPNode node, object value, PropertyOptions newOptions, bool deleteExisting)
{
if (deleteExisting)
{
node.Clear();
}
// its checked by setOptions(), if the merged result is a valid options set
node.GetOptions().MergeWith(newOptions);
if (!node.GetOptions().IsCompositeProperty())
{
// This is setting the value of a leaf node.
XMPNodeUtils.SetNodeValue(node, value);
}
else
{
if (value != null && value.ToString().Length > 0)
{
throw new XMPException("Composite nodes can't have values", XMPErrorConstants.Badxpath);
}
node.RemoveChildren();
}
}
/// <summary>
/// Evaluates a raw node value to the given value type, apply special
/// conversions for defined types in XMP.
/// </summary>
/// <param name="valueType">an int indicating the value type</param>
/// <param name="propNode">the node containing the value</param>
/// <returns>Returns a literal value for the node.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
private object EvaluateNodeValue(int valueType, XMPNode propNode)
{
object value;
string rawValue = propNode.GetValue();
switch (valueType)
{
case ValueBoolean:
{
value = XMPUtils.ConvertToBoolean(rawValue);
break;
}
case ValueInteger:
{
value = XMPUtils.ConvertToInteger(rawValue);
break;
}
case ValueLong:
{
value = XMPUtils.ConvertToLong(rawValue);
break;
}
case ValueDouble:
{
value = XMPUtils.ConvertToDouble(rawValue);
break;
}
case ValueDate:
{
value = XMPUtils.ConvertToDate(rawValue);
break;
}
case ValueCalendar:
{
XMPDateTime dt = XMPUtils.ConvertToDate(rawValue);
value = dt.GetCalendar();
break;
}
case ValueBase64:
{
value = XMPUtils.DecodeBase64(rawValue);
break;
}
case ValueString:
default:
{
// leaf values return empty string instead of null
// for the other cases the converter methods provides a "null"
// value.
// a default value can only occur if this method is made public.
value = rawValue != null || propNode.GetOptions().IsCompositeProperty() ? rawValue : string.Empty;
break;
}
}
return value;
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
public abstract partial class ExtendableBuilderLite<TMessage, TBuilder> : GeneratedBuilderLite<TMessage, TBuilder>
where TMessage : ExtendableMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder>
{
protected ExtendableBuilderLite()
{
}
/// <summary>
/// Checks if a singular extension is present
/// </summary>
public bool HasExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension)
{
return MessageBeingBuilt.HasExtension(extension);
}
/// <summary>
/// Returns the number of elements in a repeated extension.
/// </summary>
public int GetExtensionCount<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension)
{
return MessageBeingBuilt.GetExtensionCount(extension);
}
/// <summary>
/// Returns the value of an extension.
/// </summary>
public TExtension GetExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension)
{
return MessageBeingBuilt.GetExtension(extension);
}
/// <summary>
/// Returns one element of a repeated extension.
/// </summary>
public TExtension GetExtension<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension,
int index)
{
return MessageBeingBuilt.GetExtension(extension, index);
}
/// <summary>
/// Sets the value of an extension.
/// </summary>
public TBuilder SetExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension,
TExtension value)
{
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions[extension.Descriptor] = extension.ToReflectionType(value);
return ThisBuilder;
}
/// <summary>
/// Sets the value of one element of a repeated extension.
/// </summary>
public TBuilder SetExtension<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension,
int index, TExtension value)
{
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions[extension.Descriptor, index] = extension.SingularToReflectionType(value);
return ThisBuilder;
}
/// <summary>
/// Appends a value to a repeated extension.
/// </summary>
public TBuilder AddExtension<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension,
TExtension value)
{
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions.AddRepeatedField(extension.Descriptor, extension.SingularToReflectionType(value));
return ThisBuilder;
}
/// <summary>
/// Clears an extension.
/// </summary>
public TBuilder ClearExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension)
{
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions.ClearField(extension.Descriptor);
return ThisBuilder;
}
/// <summary>
/// Called by subclasses to parse an unknown field or an extension.
/// </summary>
/// <returns>true unless the tag is an end-group tag</returns>
[CLSCompliant(false)]
protected override bool ParseUnknownField(ICodedInputStream input,
ExtensionRegistry extensionRegistry, uint tag, string fieldName)
{
FieldSet extensions = MessageBeingBuilt.Extensions;
WireFormat.WireType wireType = WireFormat.GetTagWireType(tag);
int fieldNumber = WireFormat.GetTagFieldNumber(tag);
IGeneratedExtensionLite extension = extensionRegistry[DefaultInstanceForType, fieldNumber];
if (extension == null) //unknown field
{
return input.SkipField();
}
IFieldDescriptorLite field = extension.Descriptor;
// Unknown field or wrong wire type. Skip.
if (field == null)
{
return input.SkipField();
}
WireFormat.WireType expectedType = field.IsPacked
? WireFormat.WireType.LengthDelimited
: WireFormat.GetWireType(field.FieldType);
if (wireType != expectedType)
{
expectedType = WireFormat.GetWireType(field.FieldType);
if (wireType == expectedType)
{
//Allowed as of 2.3, this is unpacked data for a packed array
}
else if (field.IsRepeated && wireType == WireFormat.WireType.LengthDelimited &&
(expectedType == WireFormat.WireType.Varint || expectedType == WireFormat.WireType.Fixed32 ||
expectedType == WireFormat.WireType.Fixed64))
{
//Allowed as of 2.3, this is packed data for an unpacked array
}
else
{
return input.SkipField();
}
}
if (!field.IsRepeated && wireType != WireFormat.GetWireType(field.FieldType)) //invalid wire type
{
return input.SkipField();
}
switch (field.FieldType)
{
case FieldType.Group:
case FieldType.Message:
{
if (!field.IsRepeated)
{
IMessageLite message = extensions[extension.Descriptor] as IMessageLite;
IBuilderLite subBuilder = (message ?? extension.MessageDefaultInstance).WeakToBuilder();
if (field.FieldType == FieldType.Group)
{
input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry);
}
else
{
input.ReadMessage(subBuilder, extensionRegistry);
}
extensions[field] = subBuilder.WeakBuild();
}
else
{
List<IMessageLite> list = new List<IMessageLite>();
if (field.FieldType == FieldType.Group)
{
input.ReadGroupArray(tag, fieldName, list, extension.MessageDefaultInstance,
extensionRegistry);
}
else
{
input.ReadMessageArray(tag, fieldName, list, extension.MessageDefaultInstance,
extensionRegistry);
}
foreach (IMessageLite m in list)
{
extensions.AddRepeatedField(field, m);
}
return true;
}
break;
}
case FieldType.Enum:
{
if (!field.IsRepeated)
{
object unknown;
IEnumLite value = null;
if (input.ReadEnum(ref value, out unknown, field.EnumType))
{
extensions[field] = value;
}
}
else
{
ICollection<object> unknown;
List<IEnumLite> list = new List<IEnumLite>();
input.ReadEnumArray(tag, fieldName, list, out unknown, field.EnumType);
foreach (IEnumLite en in list)
{
extensions.AddRepeatedField(field, en);
}
}
break;
}
default:
{
if (!field.IsRepeated)
{
object value = null;
if (input.ReadPrimitiveField(field.FieldType, ref value))
{
extensions[field] = value;
}
}
else
{
List<object> list = new List<object>();
input.ReadPrimitiveArray(field.FieldType, tag, fieldName, list);
foreach (object oval in list)
{
extensions.AddRepeatedField(field, oval);
}
}
break;
}
}
return true;
}
#region Reflection
public object this[IFieldDescriptorLite field, int index]
{
set
{
if (field.IsExtension)
{
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.Extensions[field, index] = value;
}
else
{
throw new NotSupportedException("Not supported in the lite runtime.");
}
}
}
public object this[IFieldDescriptorLite field]
{
set
{
if (field.IsExtension)
{
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.Extensions[field] = value;
}
else
{
throw new NotSupportedException("Not supported in the lite runtime.");
}
}
}
public TBuilder ClearField(IFieldDescriptorLite field)
{
if (field.IsExtension)
{
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.Extensions.ClearField(field);
return ThisBuilder;
}
else
{
throw new NotSupportedException("Not supported in the lite runtime.");
}
}
public TBuilder AddRepeatedField(IFieldDescriptorLite field, object value)
{
if (field.IsExtension)
{
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.Extensions.AddRepeatedField(field, value);
return ThisBuilder;
}
else
{
throw new NotSupportedException("Not supported in the lite runtime.");
}
}
protected void MergeExtensionFields(ExtendableMessageLite<TMessage, TBuilder> other)
{
MessageBeingBuilt.Extensions.MergeFrom(other.Extensions);
}
#endregion
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
using System;
using System.Windows.Forms;
namespace IronScheme.Editor.Controls
{
class ExceptionForm : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox messageBox;
private System.Windows.Forms.TextBox detailsBox;
private System.Windows.Forms.TextBox infoBox;
private System.Windows.Forms.TextBox emailBox;
private System.Windows.Forms.TextBox nameBox;
private System.Windows.Forms.Button reportBut;
private System.Windows.Forms.Button ignoreBut;
private System.Windows.Forms.Button igallwaysBut;
private System.Windows.Forms.Button exitBut;
private System.Windows.Forms.Button checkBut;
private System.Windows.Forms.Button helpBut;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public ExceptionForm()
{
InitializeComponent();
reportBut.Enabled = false;
helpBut.Enabled = false;
detailsBox.MaxLength = 1000;
infoBox.MaxLength = 1000;
if (ComponentModel.ServiceHost.Discovery != null)
{
helpBut.Enabled = ComponentModel.ServiceHost.Discovery.NetRuntimeSDK != null;
}
igallwaysBut.Enabled = false;
nameBox.Text = Environment.UserName;
emailBox.Text = Environment.UserName + "@bugreportersanonymous.com";
infoBox.Text = Diagnostics.Trace.SystemInfo;
detailsBox.ReadOnly = false;
messageBox.Text = "Please enter your bug details below.";
exitBut.Text = "Cancel";
}
bool appstateinvalid = false;
Exception exception;
public Exception Exception
{
get {return exception;}
set
{
exception = value;
this.Text = "An unhandled exception has occured";
Exception inner = value;
messageBox.Text = inner.GetType() + Environment.NewLine + Environment.NewLine + inner.Message;
detailsBox.Text = value.ToString();
infoBox.Text = Diagnostics.Trace.GetTrace();
exitBut.Text = "Exit";
detailsBox.ReadOnly = true;
}
}
public bool ApplicationStateInvalid
{
get {return appstateinvalid;}
set
{
appstateinvalid = value;
if (value)
{
igallwaysBut.Enabled = false;
ignoreBut.Enabled = false;
}
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.messageBox = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.detailsBox = new System.Windows.Forms.TextBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.infoBox = new System.Windows.Forms.TextBox();
this.emailBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.nameBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.reportBut = new System.Windows.Forms.Button();
this.ignoreBut = new System.Windows.Forms.Button();
this.igallwaysBut = new System.Windows.Forms.Button();
this.exitBut = new System.Windows.Forms.Button();
this.checkBut = new System.Windows.Forms.Button();
this.helpBut = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.messageBox);
this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBox1.Location = new System.Drawing.Point(8, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(616, 83);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Message";
//
// messageBox
//
this.messageBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.messageBox.Location = new System.Drawing.Point(8, 18);
this.messageBox.Multiline = true;
this.messageBox.Name = "messageBox";
this.messageBox.ReadOnly = true;
this.messageBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.messageBox.Size = new System.Drawing.Size(600, 56);
this.messageBox.TabIndex = 1;
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.detailsBox);
this.groupBox2.Location = new System.Drawing.Point(8, 83);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(616, 249);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Details";
//
// detailsBox
//
this.detailsBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.detailsBox.Location = new System.Drawing.Point(8, 18);
this.detailsBox.Multiline = true;
this.detailsBox.Name = "detailsBox";
this.detailsBox.ReadOnly = true;
this.detailsBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.detailsBox.Size = new System.Drawing.Size(600, 222);
this.detailsBox.TabIndex = 0;
this.detailsBox.WordWrap = false;
//
// groupBox3
//
this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox3.Controls.Add(this.label3);
this.groupBox3.Controls.Add(this.infoBox);
this.groupBox3.Controls.Add(this.emailBox);
this.groupBox3.Controls.Add(this.label2);
this.groupBox3.Controls.Add(this.nameBox);
this.groupBox3.Controls.Add(this.label1);
this.groupBox3.Location = new System.Drawing.Point(8, 332);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(616, 305);
this.groupBox3.TabIndex = 2;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Optional";
//
// label3
//
this.label3.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label3.Location = new System.Drawing.Point(11, 77);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(599, 19);
this.label3.TabIndex = 5;
this.label3.Text = "Please supply any additional information you feel is deemed necessary (info below" +
" can be deleted at your discretion)";
//
// infoBox
//
this.infoBox.Location = new System.Drawing.Point(8, 102);
this.infoBox.Multiline = true;
this.infoBox.Name = "infoBox";
this.infoBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.infoBox.Size = new System.Drawing.Size(600, 193);
this.infoBox.TabIndex = 4;
this.infoBox.WordWrap = false;
//
// emailBox
//
this.emailBox.Location = new System.Drawing.Point(80, 46);
this.emailBox.Name = "emailBox";
this.emailBox.Size = new System.Drawing.Size(528, 22);
this.emailBox.TabIndex = 3;
//
// label2
//
this.label2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label2.Location = new System.Drawing.Point(12, 50);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 18);
this.label2.TabIndex = 2;
this.label2.Text = "Email";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// nameBox
//
this.nameBox.Location = new System.Drawing.Point(80, 18);
this.nameBox.Name = "nameBox";
this.nameBox.Size = new System.Drawing.Size(528, 22);
this.nameBox.TabIndex = 1;
//
// label1
//
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.Location = new System.Drawing.Point(11, 22);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(48, 18);
this.label1.TabIndex = 0;
this.label1.Text = "Name";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// ignoreBut
//
this.ignoreBut.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ignoreBut.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.ignoreBut.Location = new System.Drawing.Point(320, 646);
this.ignoreBut.Name = "ignoreBut";
this.ignoreBut.Size = new System.Drawing.Size(96, 27);
this.ignoreBut.TabIndex = 4;
this.ignoreBut.Text = "Ignore";
this.ignoreBut.Click += new System.EventHandler(this.ignoreBut_Click);
//
// igallwaysBut
//
this.igallwaysBut.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.igallwaysBut.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.igallwaysBut.Location = new System.Drawing.Point(424, 646);
this.igallwaysBut.Name = "igallwaysBut";
this.igallwaysBut.Size = new System.Drawing.Size(96, 27);
this.igallwaysBut.TabIndex = 5;
this.igallwaysBut.Text = "Ignore Allways";
this.igallwaysBut.Click += new System.EventHandler(this.igallwaysBut_Click);
//
// exitBut
//
this.exitBut.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.exitBut.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.exitBut.Location = new System.Drawing.Point(528, 646);
this.exitBut.Name = "exitBut";
this.exitBut.Size = new System.Drawing.Size(96, 27);
this.exitBut.TabIndex = 6;
this.exitBut.Text = "Exit";
this.exitBut.Click += new System.EventHandler(this.exitBut_Click);
//
// helpBut
//
this.helpBut.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.helpBut.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.helpBut.Location = new System.Drawing.Point(8, 646);
this.helpBut.Name = "helpBut";
this.helpBut.Size = new System.Drawing.Size(96, 27);
this.helpBut.TabIndex = 8;
this.helpBut.Text = "Break";
this.helpBut.Click += new System.EventHandler(this.helpBut_Click);
//
// ExceptionForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
this.ClientSize = new System.Drawing.Size(634, 680);
this.Controls.Add(this.helpBut);
this.Controls.Add(this.checkBut);
this.Controls.Add(this.exitBut);
this.Controls.Add(this.igallwaysBut);
this.Controls.Add(this.ignoreBut);
this.Controls.Add(this.reportBut);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ExceptionForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Submit error or bug";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
void exitBut_Click(object sender, System.EventArgs e)
{
if (exception != null)
{
Application.Exit();
}
else
{
Close();
}
}
void ignoreBut_Click(object sender, System.EventArgs e)
{
Close();
}
void igallwaysBut_Click(object sender, System.EventArgs e)
{
Close();
}
void helpBut_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Debugger.Break();
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Compiler.TypeSystem.Generics;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Compiler.TypeSystem.Reflection;
using Boo.Lang.Compiler.TypeSystem.Services;
using Boo.Lang.Compiler.Util;
using Boo.Lang.Environments;
using Attribute = System.Attribute;
using Module = Boo.Lang.Compiler.Ast.Module;
namespace Boo.Lang.Compiler.TypeSystem
{
public class TypeSystemServices
{
public static readonly IType ErrorEntity = Error.Default;
public IType ArrayType;
public IType BoolType;
public IType BuiltinsType;
public IType CharType;
public IType ConditionalAttribute;
public IType DateTimeType;
public IType DecimalType;
public IType DelegateType;
public IType DoubleType;
public IType DuckType;
public IType EnumType;
public IType HashType;
public IType IAstGeneratorMacroType;
public IType IAstMacroType;
public IType ICallableType;
public IType ICollectionGenericType;
public IType ICollectionType;
public IType IDisposableType;
public IType IEnumerableGenericType;
public IType IEnumerableType;
public IType IListGenericType;
public IType IListType;
public IType IEnumeratorGenericType;
public IType IEnumeratorType;
public IType IQuackFuType;
public IType SByteType;
public IType ShortType;
public IType IntType;
public IType IntPtrType;
public IType LongType;
public IType ByteType;
public IType UShortType;
public IType UIntType;
public IType UIntPtrType;
public IType ULongType;
public IType ListType;
public IType MulticastDelegateType;
public IArrayType ObjectArrayType;
public IType ObjectType;
public IType RegexType;
public IType RuntimeServicesType;
public IType SingleType;
public IType StringType;
public IType SystemAttribute;
public IType TimeSpanType;
public IType TypeType;
public IType ValueTypeType;
public IType VoidType;
private Module _compilerGeneratedTypesModule;
private readonly Set<string> _literalPrimitives = new Set<string>();
private readonly Dictionary<string, IEntity> _primitives = new Dictionary<string, IEntity>(StringComparer.Ordinal);
private DowncastPermissions _downcastPermissions;
private readonly MemoizedFunction<IType, IType, IMethod> _findImplicitConversionOperator;
private readonly MemoizedFunction<IType, IType, IMethod> _findExplicitConversionOperator;
private readonly MemoizedFunction<IType, IType, bool> _canBeReachedByPromotion;
private readonly AnonymousCallablesManager _anonymousCallablesManager;
private readonly CompilerContext _context;
public TypeSystemServices() : this(CompilerContext.Current)
{
}
public TypeSystemServices(CompilerContext context)
{
if (null == context) throw new ArgumentNullException("context");
_context = context;
_anonymousCallablesManager = new AnonymousCallablesManager(this);
_findImplicitConversionOperator =
new MemoizedFunction<IType, IType, IMethod>((fromType, toType) => FindConversionOperator("op_Implicit", fromType, toType));
_findExplicitConversionOperator =
new MemoizedFunction<IType, IType, IMethod>((fromType, toType) => FindConversionOperator("op_Explicit", fromType, toType));
My<CurrentScope>.Instance.Changed += (sender, args) => ClearScopeDependentMemoizedFunctions();
_canBeReachedByPromotion = new MemoizedFunction<IType, IType, bool>(CanBeReachedByPromotionImpl);
DuckType = Map(typeof(Builtins.duck));
IQuackFuType = Map(typeof(IQuackFu));
VoidType = Map(Types.Void);
ObjectType = Map(Types.Object);
RegexType = Map(Types.Regex);
ValueTypeType = Map(typeof(ValueType));
EnumType = Map(typeof(Enum));
ArrayType = Map(Types.Array);
TypeType = Map(Types.Type);
StringType = Map(Types.String);
BoolType = Map(Types.Bool);
SByteType = Map(Types.SByte);
CharType = Map(Types.Char);
ShortType = Map(Types.Short);
IntType = Map(Types.Int);
LongType = Map(Types.Long);
ByteType = Map(Types.Byte);
UShortType = Map(Types.UShort);
UIntType = Map(Types.UInt);
ULongType = Map(Types.ULong);
SingleType = Map(Types.Single);
DoubleType = Map(Types.Double);
DecimalType = Map(Types.Decimal);
TimeSpanType = Map(Types.TimeSpan);
DateTimeType = Map(Types.DateTime);
RuntimeServicesType = Map(Types.RuntimeServices);
BuiltinsType = Map(Types.Builtins);
ListType = Map(Types.List);
HashType = Map(Types.Hash);
ICallableType = Map(Types.ICallable);
IEnumerableType = Map(Types.IEnumerable);
IEnumeratorType = Map(typeof(IEnumerator));
ICollectionType = Map(Types.ICollection);
IDisposableType = Map(typeof(IDisposable));
IntPtrType = Map(Types.IntPtr);
UIntPtrType = Map(Types.UIntPtr);
MulticastDelegateType = Map(Types.MulticastDelegate);
DelegateType = Map(Types.Delegate);
SystemAttribute = Map(typeof(Attribute));
ConditionalAttribute = Map(typeof(ConditionalAttribute));
IEnumerableGenericType = Map(Types.IEnumerableGeneric);
IEnumeratorGenericType = Map(typeof(IEnumerator<>));
ICollectionGenericType = Map(typeof(ICollection<>));
IListGenericType = Map(typeof (IList<>));
IListType = Map(typeof (IList));
IAstMacroType = Map(typeof(IAstMacro));
IAstGeneratorMacroType = Map(typeof(IAstGeneratorMacro));
ObjectArrayType = ObjectType.MakeArrayType(1);
PreparePrimitives();
PrepareBuiltinFunctions();
}
private void ClearScopeDependentMemoizedFunctions()
{
_findImplicitConversionOperator.Clear();
_findExplicitConversionOperator.Clear();
}
public CompilerContext Context
{
get { return _context; }
}
public BooCodeBuilder CodeBuilder
{
get { return _context.CodeBuilder; }
}
public virtual IType ExceptionType
{
get { return Map(typeof(Exception)); }
}
public bool IsGenericGeneratorReturnType(IType returnType)
{
return returnType.ConstructedInfo != null &&
(returnType.ConstructedInfo.GenericDefinition == IEnumerableGenericType ||
returnType.ConstructedInfo.GenericDefinition == IEnumeratorGenericType);
}
public IType GetMostGenericType(ExpressionCollection args)
{
IType type = GetConcreteExpressionType(args[0]);
for (int i = 1; i < args.Count; ++i)
{
IType newType = GetConcreteExpressionType(args[i]);
if (type == newType)
continue;
type = GetMostGenericType(type, newType);
if (IsSystemObject(type))
break;
}
return type;
}
public IType GetMostGenericType(IType current, IType candidate)
{
if (null == current && null == candidate)
throw new ArgumentNullException("current", "Both 'current' and 'candidate' are null");
if (null == current)
return candidate;
if (null == candidate)
return current;
if (IsAssignableFrom(current, candidate))
return current;
if (IsAssignableFrom(candidate, current))
return candidate;
if (IsNumberOrBool(current) && IsNumberOrBool(candidate))
return GetPromotedNumberType(current, candidate);
if (IsCallableType(current) && IsCallableType(candidate))
return ICallableType;
if (current.IsClass && candidate.IsClass)
{
if (current == ObjectType || candidate == ObjectType)
return ObjectType;
if (current.GetTypeDepth() < candidate.GetTypeDepth())
return GetMostGenericType(current.BaseType, candidate);
return GetMostGenericType(current, candidate.BaseType);
}
return ObjectType;
}
public IType GetPromotedNumberType(IType left, IType right)
{
if (left == DecimalType || right == DecimalType)
return DecimalType;
if (left == DoubleType || right == DoubleType)
return DoubleType;
if (left == SingleType || right == SingleType)
return SingleType;
if (left == ULongType)
{
if (IsSignedInteger(right))
{
// This is against the C# spec but allows expressions like:
// ulong x = 4
// y = x + 1
// y will be long.
// C# disallows mixing ulongs and signed numbers
// but in the above case it promotes the constant to ulong
// and the result is ulong.
// Since its too late here to promote the constant,
// maybe we should return LongType. I didn't chose ULongType
// because in other cases <unsigned> <op> <signed> returns <signed>.
return LongType;
}
return ULongType;
}
if (right == ULongType)
{
if (IsSignedInteger(left))
{
// This is against the C# spec but allows expressions like:
// ulong x = 4
// y = 1 + x
// y will be long.
// C# disallows mixing ulongs and signed numbers
// but in the above case it promotes the constant to ulong
// and the result is ulong.
// Since its too late here to promote the constant,
// maybe we should return LongType. I didn't chose ULongType
// because in other cases <signed> <op> <unsigned> returns <signed>.
return LongType;
}
return ULongType;
}
if (left == LongType || right == LongType)
return LongType;
if (left == UIntType)
{
if (right == SByteType || right == ShortType || right == IntType)
{
// This is allowed per C# spec and y is long:
// uint x = 4
// y = x + 1
// C# promotes <uint> <op> <signed> to <long> also
// but in the above case it promotes the constant to uint first
// and the result of "x + 1" is uint.
// Since its too late here to promote the constant,
// "y = x + 1" will be long in boo.
return LongType;
}
return UIntType;
}
if (right == UIntType)
{
if (left == SByteType || left == ShortType || left == IntType)
{
// This is allowed per C# spec and y is long:
// uint x = 4
// y = 1 + x
// C# promotes <signed> <op> <uint> to <long> also
// but in the above case it promotes the constant to uint first
// and the result of "1 + x" is uint.
// Since its too late here to promote the constant,
// "y = x + 1" will be long in boo.
return LongType;
}
return UIntType;
}
if (left == IntType ||
right == IntType ||
left == ShortType ||
right == ShortType ||
left == UShortType ||
right == UShortType ||
left == ByteType ||
right == ByteType ||
left == SByteType ||
right == SByteType)
return IntType;
return left;
}
private bool IsSignedInteger(IType right)
{
return right == SByteType || right == ShortType || right == IntType || right == LongType;
}
public static bool IsReadOnlyField(IField field)
{
return field.IsInitOnly || field.IsLiteral;
}
public bool IsCallable(IType type)
{
return (TypeType == type) || IsCallableType(type) || IsDuckType(type);
}
public virtual bool IsDuckTyped(Expression expression)
{
IType type = expression.ExpressionType;
return type != null && IsDuckType(type);
}
public bool IsQuackBuiltin(Expression node)
{
return IsQuackBuiltin(node.Entity);
}
public bool IsQuackBuiltin(IEntity entity)
{
return BuiltinFunction.Quack == entity;
}
public bool IsDuckType(IType type)
{
if (type == null) throw new ArgumentNullException("type");
if (type == DuckType) return true;
if (type == ObjectType && _context.Parameters.Ducky) return true;
return KnowsQuackFu(type);
}
public bool KnowsQuackFu(IType type)
{
return type.IsSubclassOf(IQuackFuType);
}
private bool IsCallableType(IType type)
{
return (IsAssignableFrom(ICallableType, type)) || (type is ICallableType);
}
public ICallableType GetCallableType(IMethodBase method)
{
var signature = new CallableSignature(method);
return GetCallableType(signature);
}
public ICallableType GetCallableType(CallableSignature signature)
{
return _anonymousCallablesManager.GetCallableType(signature);
}
public virtual IType GetConcreteCallableType(Node sourceNode, CallableSignature signature)
{
return _anonymousCallablesManager.GetConcreteCallableType(sourceNode, signature);
}
public virtual IType GetConcreteCallableType(Node sourceNode, AnonymousCallableType anonymousType)
{
return _anonymousCallablesManager.GetConcreteCallableType(sourceNode, anonymousType);
}
public IType GetEnumeratorItemType(IType iteratorType)
{
// Arrays are enumerators of their element type
if (iteratorType.IsArray) return iteratorType.ElementType;
// String are enumerators of char
if (StringType == iteratorType) return CharType;
// Try to use an EnumerableItemType attribute
if (iteratorType.IsClass)
{
IType enumeratorItemType = GetEnumeratorItemTypeFromAttribute(iteratorType);
if (null != enumeratorItemType) return enumeratorItemType;
}
// Try to use a generic IEnumerable interface
IType genericItemType = GetGenericEnumerableItemType(iteratorType);
if (null != genericItemType) return genericItemType;
// If none of these work, the type is an enumerator of object
return ObjectType;
}
public static IType GetExpressionType(Expression node)
{
return node.ExpressionType ?? Error.Default;
}
public IType GetConcreteExpressionType(Expression expression)
{
var type = GetExpressionType(expression);
var anonymousType = type as AnonymousCallableType;
if (anonymousType != null)
{
IType concreteType = GetConcreteCallableType(expression, anonymousType);
expression.ExpressionType = concreteType;
return concreteType;
}
return type;
}
public void MapToConcreteExpressionTypes(ExpressionCollection items)
{
foreach (Expression item in items)
GetConcreteExpressionType(item);
}
public IEntity GetDefaultMember(IType type)
{
// Search for a default member on this type or any of its non-interface basetypes
for (IType t = type; t != null; t = t.BaseType)
{
IEntity member = t.GetDefaultMember();
if (member != null) return member;
}
// Search for default members on the type's interfaces
var buffer = new Set<IEntity>();
foreach (IType interfaceType in type.GetInterfaces())
{
IEntity member = GetDefaultMember(interfaceType);
if (member != null) buffer.Add(member);
}
return Entities.EntityFromList(buffer);
}
public void AddCompilerGeneratedType(TypeDefinition type)
{
GetCompilerGeneratedTypesModule().Members.Add(type);
}
public Module GetCompilerGeneratedTypesModule()
{
return _compilerGeneratedTypesModule ?? (_compilerGeneratedTypesModule = NewModule("CompilerGenerated"));
}
private Module NewModule(string nameSpace)
{
return NewModule(nameSpace, nameSpace);
}
private Module NewModule(string nameSpace, string moduleName)
{
Module module = CodeBuilder.CreateModule(moduleName, nameSpace);
_context.CompileUnit.Modules.Add(module);
return module;
}
public bool CanBeReachedFrom(IType expectedType, IType actualType)
{
bool byDowncast;
return CanBeReachedFrom(expectedType, actualType, out byDowncast);
}
public bool CanBeReachedFrom(IType expectedType, IType actualType, out bool byDowncast)
{
bool considerExplicitConversionOperators = !InStrictMode();
return CanBeReachedFrom(expectedType, actualType, considerExplicitConversionOperators, out byDowncast);
}
public bool CanBeReachedFrom(IType expectedType, IType actualType, bool considerExplicitConversionOperators, out bool byDowncast)
{
byDowncast = false;
return IsAssignableFrom(expectedType, actualType)
|| CanBeReachedByPromotion(expectedType, actualType)
|| FindImplicitConversionOperator(actualType, expectedType) != null
|| (considerExplicitConversionOperators && FindExplicitConversionOperator(actualType, expectedType) != null)
|| (byDowncast = DowncastPermissions().CanBeReachedByDowncast(expectedType, actualType));
}
private DowncastPermissions DowncastPermissions()
{
return _downcastPermissions ?? (_downcastPermissions = My<DowncastPermissions>.Instance);
}
private bool InStrictMode()
{
return _context.Parameters.Strict;
}
public IMethod FindExplicitConversionOperator(IType fromType, IType toType)
{
return _findExplicitConversionOperator.Invoke(fromType, toType);
}
public IMethod FindImplicitConversionOperator(IType fromType, IType toType)
{
return _findImplicitConversionOperator.Invoke(fromType, toType);
}
private IMethod FindConversionOperator(string name, IType fromType, IType toType)
{
while (fromType != ObjectType)
{
IMethod method = FindConversionOperator(name, fromType, toType, fromType.GetMembers());
if (null != method) return method;
method = FindConversionOperator(name, fromType, toType, toType.GetMembers());
if (null != method) return method;
method = FindConversionOperator(name, fromType, toType, FindExtension(fromType, name));
if (null != method) return method;
fromType = fromType.BaseType;
if (null == fromType) break;
}
return null;
}
private IEntity[] FindExtension(IType fromType, string name)
{
IEntity extension = NameResolutionService.ResolveExtension(fromType, name);
if (null == extension) return Ambiguous.NoEntities;
var a = extension as Ambiguous;
if (null != a) return a.Entities;
return new[] {extension};
}
private IMethod FindConversionOperator(string name, IType fromType, IType toType, IEnumerable<IEntity> candidates)
{
foreach (IMethod method in NameResolutionService.Select<IMethod>(candidates, name, EntityType.Method))
if (IsConversionOperator(method, fromType, toType)) return method;
return null;
}
protected NameResolutionService NameResolutionService
{
get { return _nameResolutionService; }
}
EnvironmentProvision<NameResolutionService> _nameResolutionService = new EnvironmentProvision<NameResolutionService>();
private static bool IsConversionOperator(IMethod method, IType fromType, IType toType)
{
if (!method.IsStatic) return false;
if (method.ReturnType != toType) return false;
IParameter[] parameters = method.GetParameters();
return (1 == parameters.Length && fromType == parameters[0].Type);
}
public bool IsCallableTypeAssignableFrom(ICallableType lhs, IType rhs)
{
if (lhs == rhs) return true;
if (rhs.IsNull()) return true;
var other = rhs as ICallableType;
if (null == other) return false;
CallableSignature lvalue = lhs.GetSignature();
CallableSignature rvalue = other.GetSignature();
if (lvalue == rvalue) return true;
IParameter[] lparams = lvalue.Parameters;
IParameter[] rparams = rvalue.Parameters;
if (lparams.Length < rparams.Length) return false;
for (int i = 0; i < rparams.Length; ++i)
if (!CanBeReachedFrom(lparams[i].Type, rparams[i].Type))
return false;
return CompatibleReturnTypes(lvalue, rvalue);
}
private bool CompatibleReturnTypes(CallableSignature lvalue, CallableSignature rvalue)
{
if (VoidType != lvalue.ReturnType && VoidType != rvalue.ReturnType)
return CanBeReachedFrom(lvalue.ReturnType, rvalue.ReturnType);
return true;
}
public static bool CheckOverrideSignature(IMethod impl, IMethod baseMethod)
{
if (!GenericsServices.AreOfSameGenerity(impl, baseMethod))
return false;
CallableSignature baseSignature = GetOverriddenSignature(baseMethod, impl);
return CheckOverrideSignature(impl.GetParameters(), baseSignature.Parameters);
}
public static bool CheckOverrideSignature(IParameter[] implParameters, IParameter[] baseParameters)
{
return CallableSignature.AreSameParameters(implParameters, baseParameters);
}
public static CallableSignature GetOverriddenSignature(IMethod baseMethod, IMethod impl)
{
if (baseMethod.GenericInfo != null && GenericsServices.AreOfSameGenerity(baseMethod, impl))
return baseMethod.GenericInfo.ConstructMethod(impl.GenericInfo.GenericParameters).CallableType.GetSignature();
return baseMethod.CallableType.GetSignature();
}
public virtual bool CanBeReachedByDownCastOrPromotion(IType expectedType, IType actualType)
{
return DowncastPermissions().CanBeReachedByDowncast(expectedType, actualType)
|| CanBeReachedByPromotion(expectedType, actualType);
}
public virtual bool CanBeReachedByPromotion(IType expectedType, IType actualType)
{
return _canBeReachedByPromotion.Invoke(expectedType, actualType);
}
private bool CanBeReachedByPromotionImpl(IType expectedType, IType actualType)
{
if (IsNullable(expectedType) && actualType.IsNull())
return true;
if (IsIntegerNumber(actualType) && CanBeExplicitlyCastToInteger(expectedType))
return true;
if (IsIntegerNumber(expectedType) && CanBeExplicitlyCastToInteger(actualType))
return true;
return (expectedType.IsValueType && IsNumber(expectedType) && IsNumber(actualType));
}
public bool CanBeExplicitlyCastToInteger(IType type)
{
return type.IsEnum || type == CharType;
}
public static bool ContainsMethodsOnly(ICollection<IEntity> members)
{
return members.All(member => EntityType.Method == member.EntityType);
}
public bool IsIntegerNumber(IType type)
{
return IsSignedInteger(type) || IsUnsignedInteger(type);
}
private bool IsUnsignedInteger(IType type)
{
return (type == UShortType ||
type == UIntType ||
type == ULongType ||
type == ByteType);
}
public bool IsIntegerOrBool(IType type)
{
return BoolType == type || IsIntegerNumber(type);
}
public bool IsNumberOrBool(IType type)
{
return BoolType == type || IsNumber(type);
}
public bool IsNumber(IType type)
{
return IsPrimitiveNumber(type) || type == DecimalType;
}
public bool IsPrimitiveNumber(IType type)
{
return IsIntegerNumber(type) || type == DoubleType || type == SingleType;
}
public bool IsSignedNumber(IType type)
{
return IsNumber(type) && !IsUnsignedInteger(type);
}
/// <summary>
/// Returns true if the type is a reference type or a generic parameter
/// type that is constrained to represent a reference type.
/// </summary>
public static bool IsReferenceType(IType type)
{
var gp = type as IGenericParameter;
if (null == gp)
return !type.IsValueType;
if (gp.IsClass)
return true;
foreach (IType tc in gp.GetTypeConstraints())
if (!tc.IsValueType && !tc.IsInterface)
return true;
return false;
}
/// <summary>
/// Returns true if the type can be either a reference type or a value type.
/// Currently it returns true only for an unconstrained generic parameter type.
/// </summary>
public static bool IsAnyType(IType type)
{
var gp = type as IGenericParameter;
return (null != gp && !gp.IsClass && !gp.IsValueType && 0 == gp.GetTypeConstraints().Length);
}
public static bool IsNullable(IType type)
{
var et = type as ExternalType;
return (null != et && et.ActualType.IsGenericType && et.ActualType.GetGenericTypeDefinition() == Types.Nullable);
}
public IType GetNullableUnderlyingType(IType type)
{
var et = type as ExternalType;
return Map(Nullable.GetUnderlyingType(et.ActualType));
}
public static bool IsUnknown(Expression node)
{
var type = node.ExpressionType;
return null != type && IsUnknown(type);
}
public static bool IsUnknown(IType type)
{
return EntityType.Unknown == type.EntityType;
}
public static bool IsError(Expression node)
{
var type = node.ExpressionType;
return null != type && IsError(type);
}
public static bool IsErrorAny(ExpressionCollection collection)
{
return collection.Any(IsError);
}
public bool IsBuiltin(IEntity entity)
{
if (EntityType.Method == entity.EntityType)
return BuiltinsType == ((IMethod) entity).DeclaringType;
return false;
}
public static bool IsError(IEntity entity)
{
return EntityType.Error == entity.EntityType;
}
public static TypeMemberModifiers GetAccess(IAccessibleMember member)
{
if (member.IsPublic)
return TypeMemberModifiers.Public;
if (member.IsProtected)
{
if (member.IsInternal)
return TypeMemberModifiers.Protected | TypeMemberModifiers.Internal;
return TypeMemberModifiers.Protected;
}
if (member.IsInternal)
return TypeMemberModifiers.Internal;
return TypeMemberModifiers.Private;
}
[Obsolete("Use Node.Entity instead.")]
public static IEntity GetOptionalEntity(Node node)
{
return node.Entity;
}
public static IEntity GetEntity(Node node)
{
var entity = node.Entity;
if (entity != null)
return entity;
if (My<CompilerParameters>.Instance.Pipeline.BreakOnErrors)
InvalidNode(node);
return Error.Default;
}
public static IType GetReferencedType(Expression typeref)
{
switch (typeref.NodeType)
{
case NodeType.TypeofExpression:
return GetType(((TypeofExpression) typeref).Type);
case NodeType.ReferenceExpression:
case NodeType.MemberReferenceExpression:
case NodeType.GenericReferenceExpression:
return typeref.Entity as IType;
}
return null;
}
public bool IsAttribute(IType type)
{
return type.IsSubclassOf(SystemAttribute);
}
public static IType GetType(Node node)
{
return ((ITypedEntity) GetEntity(node)).Type;
}
public IType Map(Type type)
{
return TypeSystemProvider().Map(type);
}
private IReflectionTypeSystemProvider TypeSystemProvider()
{
return _typeSystemProvider.Instance;
}
private EnvironmentProvision<IReflectionTypeSystemProvider> _typeSystemProvider;
public IParameter[] Map(ParameterInfo[] parameters)
{
return TypeSystemProvider().Map(parameters);
}
public IConstructor Map(ConstructorInfo constructor)
{
return (IConstructor) Map((MemberInfo) constructor);
}
public IMethod Map(MethodInfo method)
{
return (IMethod) Map((MemberInfo) method);
}
public IEntity Map(MemberInfo[] members)
{
return TypeSystemProvider().Map(members);
}
public IEntity Map(MemberInfo mi)
{
return TypeSystemProvider().Map(mi);
}
public static string GetSignature(IEntityWithParameters method)
{
return My<EntityFormatter>.Instance.FormatSignature(method);
}
public IEntity ResolvePrimitive(string name)
{
IEntity result;
if (_primitives.TryGetValue(name, out result))
return result;
return null;
}
public bool IsPrimitive(string name)
{
return _primitives.ContainsKey(name);
}
public bool IsLiteralPrimitive(IType type)
{
var typ = type as ExternalType;
return typ != null
&& typ.PrimitiveName != null
&& _literalPrimitives.Contains(typ.PrimitiveName);
}
/// <summary>
/// checks if the passed type will be equivalente to
/// System.Object in runtime (accounting for the presence
/// of duck typing).
/// </summary>
public bool IsSystemObject(IType type)
{
return type == ObjectType || type == DuckType;
}
public bool IsPointerCompatible(IType type)
{
return IsPrimitiveNumber(type) || (type.IsValueType && 0 != SizeOf(type));
}
protected virtual void PreparePrimitives()
{
AddPrimitiveType("duck", DuckType);
AddPrimitiveType("void", VoidType);
AddPrimitiveType("object", ObjectType);
AddPrimitiveType("callable", ICallableType);
AddPrimitiveType("decimal", DecimalType);
AddPrimitiveType("date", DateTimeType);
AddLiteralPrimitiveType("bool", BoolType);
AddLiteralPrimitiveType("sbyte", SByteType);
AddLiteralPrimitiveType("byte", ByteType);
AddLiteralPrimitiveType("short", ShortType);
AddLiteralPrimitiveType("ushort", UShortType);
AddLiteralPrimitiveType("int", IntType);
AddLiteralPrimitiveType("uint", UIntType);
AddLiteralPrimitiveType("long", LongType);
AddLiteralPrimitiveType("ulong", ULongType);
AddLiteralPrimitiveType("single", SingleType);
AddLiteralPrimitiveType("double", DoubleType);
AddLiteralPrimitiveType("char", CharType);
AddLiteralPrimitiveType("string", StringType);
AddLiteralPrimitiveType("regex", RegexType);
AddLiteralPrimitiveType("timespan", TimeSpanType);
}
protected virtual void PrepareBuiltinFunctions()
{
AddBuiltin(BuiltinFunction.Len);
AddBuiltin(BuiltinFunction.AddressOf);
AddBuiltin(BuiltinFunction.Eval);
AddBuiltin(BuiltinFunction.Switch);
}
protected void AddPrimitiveType(string name, IType type)
{
_primitives[name] = type;
((ExternalType) type).PrimitiveName = name;
}
protected void AddLiteralPrimitiveType(string name, IType type)
{
AddPrimitiveType(name, type);
_literalPrimitives.Add(name);
}
protected void AddBuiltin(BuiltinFunction function)
{
_primitives[function.Name] = function;
}
public IConstructor GetDefaultConstructor(IType type)
{
return type.GetConstructors().FirstOrDefault(constructor => 0 == constructor.GetParameters().Length);
}
private IType GetExternalEnumeratorItemType(IType iteratorType)
{
Type type = ((ExternalType) iteratorType).ActualType;
var attribute = (EnumeratorItemTypeAttribute) Attribute.GetCustomAttribute(type, typeof(EnumeratorItemTypeAttribute));
return null != attribute ? Map(attribute.ItemType) : null;
}
private IType GetEnumeratorItemTypeFromAttribute(IType iteratorType)
{
// If iterator type is external get its attributes via reflection
if (iteratorType is ExternalType)
return GetExternalEnumeratorItemType(iteratorType);
// If iterator type is a generic constructed type, get its attribute from its definition
// and map generic parameters
if (iteratorType.ConstructedInfo != null)
{
IType definitionItemType = GetEnumeratorItemType(iteratorType.ConstructedInfo.GenericDefinition);
return iteratorType.ConstructedInfo.Map(definitionItemType);
}
// If iterator type is internal get its attributes from its type definition
var internalType = (AbstractInternalType) iteratorType;
IType enumeratorItemTypeAttribute = Map(typeof(EnumeratorItemTypeAttribute));
foreach (Ast.Attribute attribute in internalType.TypeDefinition.Attributes)
{
var constructor = GetEntity(attribute) as IConstructor;
if (null != constructor && constructor.DeclaringType == enumeratorItemTypeAttribute)
return GetType(attribute.Arguments[0]);
}
return null;
}
public IType GetGenericEnumerableItemType(IType iteratorType)
{
// Arrays implicitly implement IEnumerable[of element type]
if (iteratorType is ArrayType) return iteratorType.ElementType;
// If type is not an array, try to find IEnumerable[of some type] in its interfaces
IType itemType = null;
foreach (IType type in GenericsServices.FindConstructedTypes(iteratorType, IEnumerableGenericType))
{
IType candidateItemType = type.ConstructedInfo.GenericArguments[0];
if (itemType != null)
itemType = GetMostGenericType(itemType, candidateItemType);
else
itemType = candidateItemType;
}
return itemType;
}
private static void InvalidNode(Node node)
{
throw CompilerErrorFactory.InvalidNode(node);
}
public virtual bool IsValidException(IType type)
{
return IsAssignableFrom(ExceptionType, type);
}
private static bool IsAssignableFrom(IType expectedType, IType actualType)
{
return TypeCompatibilityRules.IsAssignableFrom(expectedType, actualType);
}
public virtual IConstructor GetStringExceptionConstructor()
{
return Map(typeof(Exception).GetConstructor(new[] {typeof(string)}));
}
public virtual bool IsMacro(IType type)
{
return type.IsSubclassOf(IAstMacroType) || type.IsSubclassOf(IAstGeneratorMacroType);
}
public virtual int SizeOf(IType type)
{
if (type.IsPointer)
type = type.ElementType;
if (null == type || !type.IsValueType)
return 0;
var et = type as ExternalType;
if (null != et)
return Marshal.SizeOf(et.ActualType);
int size = 0;
var it = type as InternalClass;
if (null == it)
return 0;
//FIXME: TODO: warning if no predefined size => StructLayoutAttribute
foreach (Field f in it.TypeDefinition.Members.OfType<Field>())
{
int fsize = SizeOf(f.Type.Entity as IType);
if (0 == fsize)
return 0; //cannot be unmanaged
size += fsize;
}
return size;
}
public IType MapWildcardType(IType type)
{
if (type.IsNull())
return ObjectType;
if (EmptyArrayType.Default == type)
return ObjectArrayType;
return type;
}
}
}
| |
/*
* Copyright (c) 2000 - 2015 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org)
*/
using System;
using Org.BouncyCastle.Crypto.Utilities;
namespace Org.BouncyCastle.Crypto.Digests
{
/**
* implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
*/
public class MD5Digest
: GeneralDigest
{
private const int DigestLength = 16;
private uint H1, H2, H3, H4; // IV's
private uint[] X = new uint[16];
private int xOff;
public MD5Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public MD5Digest(MD5Digest t)
: base(t)
{
CopyIn(t);
}
private void CopyIn(MD5Digest t)
{
base.CopyIn(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "MD5"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff] = Pack.LE_To_UInt32(input, inOff);
if (++xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
if (xOff == 15)
X[15] = 0;
ProcessBlock();
}
for (int i = xOff; i < 14; ++i)
{
X[i] = 0;
}
X[14] = (uint)((ulong)bitLength);
X[15] = (uint)((ulong)bitLength >> 32);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_LE(H1, output, outOff);
Pack.UInt32_To_LE(H2, output, outOff + 4);
Pack.UInt32_To_LE(H3, output, outOff + 8);
Pack.UInt32_To_LE(H4, output, outOff + 12);
Reset();
return DigestLength;
}
/**
* reset the chaining variables to the IV values.
*/
public override void Reset()
{
base.Reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
xOff = 0;
for (int i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
//
// round 1 left rotates
//
private static readonly int S11 = 7;
private static readonly int S12 = 12;
private static readonly int S13 = 17;
private static readonly int S14 = 22;
//
// round 2 left rotates
//
private static readonly int S21 = 5;
private static readonly int S22 = 9;
private static readonly int S23 = 14;
private static readonly int S24 = 20;
//
// round 3 left rotates
//
private static readonly int S31 = 4;
private static readonly int S32 = 11;
private static readonly int S33 = 16;
private static readonly int S34 = 23;
//
// round 4 left rotates
//
private static readonly int S41 = 6;
private static readonly int S42 = 10;
private static readonly int S43 = 15;
private static readonly int S44 = 21;
/*
* rotate int x left n bits.
*/
private static uint RotateLeft(
uint x,
int n)
{
return (x << n) | (x >> (32 - n));
}
/*
* F, G, H and I are the basic MD5 functions.
*/
private static uint F(
uint u,
uint v,
uint w)
{
return (u & v) | (~u & w);
}
private static uint G(
uint u,
uint v,
uint w)
{
return (u & w) | (v & ~w);
}
private static uint H(
uint u,
uint v,
uint w)
{
return u ^ v ^ w;
}
private static uint K(
uint u,
uint v,
uint w)
{
return v ^ (u | ~w);
}
internal override void ProcessBlock()
{
uint a = H1;
uint b = H2;
uint c = H3;
uint d = H4;
//
// Round 1 - F cycle, 16 times.
//
a = RotateLeft((a + F(b, c, d) + X[0] + 0xd76aa478), S11) + b;
d = RotateLeft((d + F(a, b, c) + X[1] + 0xe8c7b756), S12) + a;
c = RotateLeft((c + F(d, a, b) + X[2] + 0x242070db), S13) + d;
b = RotateLeft((b + F(c, d, a) + X[3] + 0xc1bdceee), S14) + c;
a = RotateLeft((a + F(b, c, d) + X[4] + 0xf57c0faf), S11) + b;
d = RotateLeft((d + F(a, b, c) + X[5] + 0x4787c62a), S12) + a;
c = RotateLeft((c + F(d, a, b) + X[6] + 0xa8304613), S13) + d;
b = RotateLeft((b + F(c, d, a) + X[7] + 0xfd469501), S14) + c;
a = RotateLeft((a + F(b, c, d) + X[8] + 0x698098d8), S11) + b;
d = RotateLeft((d + F(a, b, c) + X[9] + 0x8b44f7af), S12) + a;
c = RotateLeft((c + F(d, a, b) + X[10] + 0xffff5bb1), S13) + d;
b = RotateLeft((b + F(c, d, a) + X[11] + 0x895cd7be), S14) + c;
a = RotateLeft((a + F(b, c, d) + X[12] + 0x6b901122), S11) + b;
d = RotateLeft((d + F(a, b, c) + X[13] + 0xfd987193), S12) + a;
c = RotateLeft((c + F(d, a, b) + X[14] + 0xa679438e), S13) + d;
b = RotateLeft((b + F(c, d, a) + X[15] + 0x49b40821), S14) + c;
//
// Round 2 - G cycle, 16 times.
//
a = RotateLeft((a + G(b, c, d) + X[1] + 0xf61e2562), S21) + b;
d = RotateLeft((d + G(a, b, c) + X[6] + 0xc040b340), S22) + a;
c = RotateLeft((c + G(d, a, b) + X[11] + 0x265e5a51), S23) + d;
b = RotateLeft((b + G(c, d, a) + X[0] + 0xe9b6c7aa), S24) + c;
a = RotateLeft((a + G(b, c, d) + X[5] + 0xd62f105d), S21) + b;
d = RotateLeft((d + G(a, b, c) + X[10] + 0x02441453), S22) + a;
c = RotateLeft((c + G(d, a, b) + X[15] + 0xd8a1e681), S23) + d;
b = RotateLeft((b + G(c, d, a) + X[4] + 0xe7d3fbc8), S24) + c;
a = RotateLeft((a + G(b, c, d) + X[9] + 0x21e1cde6), S21) + b;
d = RotateLeft((d + G(a, b, c) + X[14] + 0xc33707d6), S22) + a;
c = RotateLeft((c + G(d, a, b) + X[3] + 0xf4d50d87), S23) + d;
b = RotateLeft((b + G(c, d, a) + X[8] + 0x455a14ed), S24) + c;
a = RotateLeft((a + G(b, c, d) + X[13] + 0xa9e3e905), S21) + b;
d = RotateLeft((d + G(a, b, c) + X[2] + 0xfcefa3f8), S22) + a;
c = RotateLeft((c + G(d, a, b) + X[7] + 0x676f02d9), S23) + d;
b = RotateLeft((b + G(c, d, a) + X[12] + 0x8d2a4c8a), S24) + c;
//
// Round 3 - H cycle, 16 times.
//
a = RotateLeft((a + H(b, c, d) + X[5] + 0xfffa3942), S31) + b;
d = RotateLeft((d + H(a, b, c) + X[8] + 0x8771f681), S32) + a;
c = RotateLeft((c + H(d, a, b) + X[11] + 0x6d9d6122), S33) + d;
b = RotateLeft((b + H(c, d, a) + X[14] + 0xfde5380c), S34) + c;
a = RotateLeft((a + H(b, c, d) + X[1] + 0xa4beea44), S31) + b;
d = RotateLeft((d + H(a, b, c) + X[4] + 0x4bdecfa9), S32) + a;
c = RotateLeft((c + H(d, a, b) + X[7] + 0xf6bb4b60), S33) + d;
b = RotateLeft((b + H(c, d, a) + X[10] + 0xbebfbc70), S34) + c;
a = RotateLeft((a + H(b, c, d) + X[13] + 0x289b7ec6), S31) + b;
d = RotateLeft((d + H(a, b, c) + X[0] + 0xeaa127fa), S32) + a;
c = RotateLeft((c + H(d, a, b) + X[3] + 0xd4ef3085), S33) + d;
b = RotateLeft((b + H(c, d, a) + X[6] + 0x04881d05), S34) + c;
a = RotateLeft((a + H(b, c, d) + X[9] + 0xd9d4d039), S31) + b;
d = RotateLeft((d + H(a, b, c) + X[12] + 0xe6db99e5), S32) + a;
c = RotateLeft((c + H(d, a, b) + X[15] + 0x1fa27cf8), S33) + d;
b = RotateLeft((b + H(c, d, a) + X[2] + 0xc4ac5665), S34) + c;
//
// Round 4 - K cycle, 16 times.
//
a = RotateLeft((a + K(b, c, d) + X[0] + 0xf4292244), S41) + b;
d = RotateLeft((d + K(a, b, c) + X[7] + 0x432aff97), S42) + a;
c = RotateLeft((c + K(d, a, b) + X[14] + 0xab9423a7), S43) + d;
b = RotateLeft((b + K(c, d, a) + X[5] + 0xfc93a039), S44) + c;
a = RotateLeft((a + K(b, c, d) + X[12] + 0x655b59c3), S41) + b;
d = RotateLeft((d + K(a, b, c) + X[3] + 0x8f0ccc92), S42) + a;
c = RotateLeft((c + K(d, a, b) + X[10] + 0xffeff47d), S43) + d;
b = RotateLeft((b + K(c, d, a) + X[1] + 0x85845dd1), S44) + c;
a = RotateLeft((a + K(b, c, d) + X[8] + 0x6fa87e4f), S41) + b;
d = RotateLeft((d + K(a, b, c) + X[15] + 0xfe2ce6e0), S42) + a;
c = RotateLeft((c + K(d, a, b) + X[6] + 0xa3014314), S43) + d;
b = RotateLeft((b + K(c, d, a) + X[13] + 0x4e0811a1), S44) + c;
a = RotateLeft((a + K(b, c, d) + X[4] + 0xf7537e82), S41) + b;
d = RotateLeft((d + K(a, b, c) + X[11] + 0xbd3af235), S42) + a;
c = RotateLeft((c + K(d, a, b) + X[2] + 0x2ad7d2bb), S43) + d;
b = RotateLeft((b + K(c, d, a) + X[9] + 0xeb86d391), S44) + c;
H1 += a;
H2 += b;
H3 += c;
H4 += d;
xOff = 0;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Avro.IO;
using System.IO;
namespace Avro.Generic
{
public delegate T Reader<T>();
/// <summary>
/// A general purpose reader of data from avro streams. This can optionally resolve if the reader's and writer's
/// schemas are different. This class is a wrapper around DefaultReader and offers a little more type safety. The default reader
/// has the flexibility to return any type of object for each read call because the Read() method is generic. This
/// class on the other hand can only return a single type because the type is a parameter to the class. Any
/// user defined extension should, however, be done to DefaultReader. This class is sealed.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class GenericReader<T> : DatumReader<T>
{
private readonly DefaultReader reader;
/// <summary>
/// Constructs a generic reader for the given schemas using the DefaultReader. If the
/// reader's and writer's schemas are different this class performs the resolution.
/// </summary>
/// <param name="writerSchema">The schema used while generating the data</param>
/// <param name="readerSchema">The schema desired by the reader</param>
public GenericReader(Schema writerSchema, Schema readerSchema)
: this(new DefaultReader(writerSchema, readerSchema))
{
}
/// <summary>
/// Constructs a generic reader by directly using the given DefaultReader
/// </summary>
/// <param name="reader">The actual reader to use</param>
public GenericReader(DefaultReader reader)
{
this.reader = reader;
}
public Schema WriterSchema { get { return reader.WriterSchema; } }
public Schema ReaderSchema { get { return reader.ReaderSchema; } }
public T Read(T reuse, Decoder d)
{
return reader.Read(reuse, d);
}
}
/// <summary>
/// The default implementation for the generic reader. It constructs new .NET objects for avro objects on the
/// stream and returns the .NET object. Users can directly use this class or, if they want to customize the
/// object types for differnt Avro schema types, can derive from this class. There are enough hooks in this
/// class to allow customization.
/// </summary>
/// <remarks>
/// <list type="table">
/// <listheader><term>Avro Type</term><description>.NET Type</description></listheader>
/// <item><term>null</term><description>null reference</description></item>
/// </list>
/// </remarks>
public class DefaultReader
{
public Schema ReaderSchema { get; private set; }
public Schema WriterSchema { get; private set; }
/// <summary>
/// Constructs the default reader for the given schemas using the DefaultReader. If the
/// reader's and writer's schemas are different this class performs the resolution.
/// This default implemenation maps Avro types to .NET types as follows:
/// </summary>
/// <param name="writerSchema">The schema used while generating the data</param>
/// <param name="readerSchema">The schema desired by the reader</param>
public DefaultReader(Schema writerSchema, Schema readerSchema)
{
this.ReaderSchema = readerSchema;
this.WriterSchema = writerSchema;
}
/// <summary>
/// Reads an object off the stream.
/// </summary>
/// <typeparam name="T">The type of object to read. A single schema typically returns an object of a single .NET class.
/// The only exception is UnionSchema, which can return a object of different types based on the branch selected.
/// </typeparam>
/// <param name="reuse">If not null, the implemenation will try to use to return the object</param>
/// <param name="decoder">The decoder for deserialization</param>
/// <returns></returns>
public T Read<T>(T reuse, Decoder decoder)
{
if (!ReaderSchema.CanRead(WriterSchema))
throw new AvroException("Schema mismatch. Reader: " + ReaderSchema + ", writer: " + WriterSchema);
return (T)Read(reuse, WriterSchema, ReaderSchema, decoder);
}
public object Read(object reuse, Schema writerSchema, Schema readerSchema, Decoder d)
{
if (readerSchema.Tag == Schema.Type.Union && writerSchema.Tag != Schema.Type.Union)
{
readerSchema = findBranch(readerSchema as UnionSchema, writerSchema);
}
/*
if (!readerSchema.CanRead(writerSchema))
{
throw new AvroException("Schema mismatch. Reader: " + readerSchema + ", writer: " + writerSchema);
}
*/
switch (writerSchema.Tag)
{
case Schema.Type.Null:
return ReadNull(readerSchema, d);
case Schema.Type.Boolean:
return Read<bool>(writerSchema.Tag, readerSchema, d.ReadBoolean);
case Schema.Type.Int:
{
int i = Read<int>(writerSchema.Tag, readerSchema, d.ReadInt);
switch (readerSchema.Tag)
{
case Schema.Type.Long:
return (long)i;
case Schema.Type.Float:
return (float)i;
case Schema.Type.Double:
return (double)i;
default:
return i;
}
}
case Schema.Type.Long:
{
long l = Read<long>(writerSchema.Tag, readerSchema, d.ReadLong);
switch (readerSchema.Tag)
{
case Schema.Type.Float:
return (float)l;
case Schema.Type.Double:
return (double)l;
default:
return l;
}
}
case Schema.Type.Float:
{
float f = Read<float>(writerSchema.Tag, readerSchema, d.ReadFloat);
switch (readerSchema.Tag)
{
case Schema.Type.Double:
return (double)f;
default:
return f;
}
}
case Schema.Type.Double:
return Read<double>(writerSchema.Tag, readerSchema, d.ReadDouble);
case Schema.Type.String:
return Read<string>(writerSchema.Tag, readerSchema, d.ReadString);
case Schema.Type.Bytes:
return Read<byte[]>(writerSchema.Tag, readerSchema, d.ReadBytes);
case Schema.Type.Record:
return ReadRecord(reuse, (RecordSchema)writerSchema, readerSchema, d);
case Schema.Type.Enumeration:
return ReadEnum(reuse, (EnumSchema)writerSchema, readerSchema, d);
case Schema.Type.Fixed:
return ReadFixed(reuse, (FixedSchema)writerSchema, readerSchema, d);
case Schema.Type.Array:
return ReadArray(reuse, (ArraySchema)writerSchema, readerSchema, d);
case Schema.Type.Map:
return ReadMap(reuse, (MapSchema)writerSchema, readerSchema, d);
case Schema.Type.Union:
return ReadUnion(reuse, (UnionSchema)writerSchema, readerSchema, d);
default:
throw new AvroException("Unknown schema type: " + writerSchema);
}
}
/// <summary>
/// Deserializes a null from the stream.
/// </summary>
/// <param name="readerSchema">Reader's schema, which should be a NullSchema</param>
/// <param name="d">The decoder for deserialization</param>
/// <returns></returns>
protected virtual object ReadNull(Schema readerSchema, Decoder d)
{
d.ReadNull();
return null;
}
/// <summary>
/// A generic function to read primitive types
/// </summary>
/// <typeparam name="S">The .NET type to read</typeparam>
/// <param name="tag">The Avro type tag for the object on the stream</param>
/// <param name="readerSchema">A schema compatible to the Avro type</param>
/// <param name="reader">A function that can read the avro type from the stream</param>
/// <returns>The primitive type just read</returns>
protected S Read<S>(Schema.Type tag, Schema readerSchema, Reader<S> reader)
{
return reader();
}
/// <summary>
/// Deserializes a record from the stream.
/// </summary>
/// <param name="reuse">If not null, a record object that could be reused for returning the result</param>
/// <param name="writerSchema">The writer's RecordSchema</param>
/// <param name="readerSchema">The reader's schema, must be RecordSchema too.</param>
/// <param name="dec">The decoder for deserialization</param>
/// <returns>The record object just read</returns>
protected virtual object ReadRecord(object reuse, RecordSchema writerSchema, Schema readerSchema, Decoder dec)
{
RecordSchema rs = (RecordSchema)readerSchema;
object rec = CreateRecord(reuse, rs);
foreach (Field wf in writerSchema)
{
try
{
Field rf;
if (rs.TryGetFieldAlias(wf.Name, out rf))
{
object obj = null;
TryGetField(rec, wf.Name, rf.Pos, out obj);
AddField(rec, wf.Name, rf.Pos, Read(obj, wf.Schema, rf.Schema, dec));
}
else
Skip(wf.Schema, dec);
}
catch (Exception ex)
{
throw new AvroException(ex.Message + " in field " + wf.Name);
}
}
var defaultStream = new MemoryStream();
var defaultEncoder = new BinaryEncoder(defaultStream);
var defaultDecoder = new BinaryDecoder(defaultStream);
foreach (Field rf in rs)
{
if (writerSchema.Contains(rf.Name)) continue;
defaultStream.Position = 0; // reset for writing
Resolver.EncodeDefaultValue(defaultEncoder, rf.Schema, rf.DefaultValue);
defaultStream.Flush();
defaultStream.Position = 0; // reset for reading
object obj = null;
TryGetField(rec, rf.Name, rf.Pos, out obj);
AddField(rec, rf.Name, rf.Pos, Read(obj, rf.Schema, rf.Schema, defaultDecoder));
}
return rec;
}
/// <summary>
/// Creates a new record object. Derived classes can override this to return an object of their choice.
/// </summary>
/// <param name="reuse">If appropriate, will reuse this object instead of constructing a new one</param>
/// <param name="readerSchema">The schema the reader is using</param>
/// <returns></returns>
protected virtual object CreateRecord(object reuse, RecordSchema readerSchema)
{
GenericRecord ru = (reuse == null || !(reuse is GenericRecord) || !(reuse as GenericRecord).Schema.Equals(readerSchema)) ?
new GenericRecord(readerSchema) :
reuse as GenericRecord;
return ru;
}
/// <summary>
/// Used by the default implementation of ReadRecord() to get the existing field of a record object. The derived
/// classes can override this to make their own interpretation of the record object.
/// </summary>
/// <param name="record">The record object to be probed into. This is guaranteed to be one that was returned
/// by a previous call to CreateRecord.</param>
/// <param name="fieldName">The name of the field to probe.</param>
/// <param name="value">The value of the field, if found. Null otherwise.</param>
/// <returns>True if and only if a field with the given name is found.</returns>
protected virtual bool TryGetField(object record, string fieldName, int fieldPos, out object value)
{
return (record as GenericRecord).TryGetValue(fieldName, out value);
}
/// <summary>
/// Used by the default implementation of ReadRecord() to add a field to a record object. The derived
/// classes can override this to suit their own implementation of the record object.
/// </summary>
/// <param name="record">The record object to be probed into. This is guaranteed to be one that was returned
/// by a previous call to CreateRecord.</param>
/// <param name="fieldName">The name of the field to probe.</param>
/// <param name="fieldValue">The value to be added for the field</param>
protected virtual void AddField(object record, string fieldName, int fieldPos, object fieldValue)
{
(record as GenericRecord).Add(fieldName, fieldValue);
}
/// <summary>
/// Deserializes a enum. Uses CreateEnum to construct the new enum object.
/// </summary>
/// <param name="reuse">If appropirate, uses this instead of creating a new enum object.</param>
/// <param name="writerSchema">The schema the writer used while writing the enum</param>
/// <param name="readerSchema">The schema the reader is using</param>
/// <param name="d">The decoder for deserialization.</param>
/// <returns>An enum object.</returns>
protected virtual object ReadEnum(object reuse, EnumSchema writerSchema, Schema readerSchema, Decoder d)
{
EnumSchema es = readerSchema as EnumSchema;
return CreateEnum(reuse, readerSchema as EnumSchema, writerSchema[d.ReadEnum()]);
}
/// <summary>
/// Used by the default implementation of ReadEnum to construct a new enum object.
/// </summary>
/// <param name="reuse">If appropriate, use this enum object instead of a new one.</param>
/// <param name="es">The enum schema used by the reader.</param>
/// <param name="symbol">The symbol that needs to be used.</param>
/// <returns>The default implemenation returns a GenericEnum.</returns>
protected virtual object CreateEnum(object reuse, EnumSchema es, string symbol)
{
if (reuse is GenericEnum)
{
GenericEnum ge = reuse as GenericEnum;
if (ge.Schema.Equals(es))
{
ge.Value = symbol;
return ge;
}
}
return new GenericEnum(es, symbol);
}
/// <summary>
/// Deserializes an array and returns an array object. It uses CreateArray() and works on it before returning it.
/// It also uses GetArraySize(), ResizeArray(), SetArrayElement() and GetArrayElement() methods. Derived classes can
/// override these methods to customize their behavior.
/// </summary>
/// <param name="reuse">If appropriate, uses this instead of creating a new array object.</param>
/// <param name="writerSchema">The schema used by the writer.</param>
/// <param name="readerSchema">The schema that the reader uses.</param>
/// <param name="d">The decoder for deserialization.</param>
/// <returns>The deserialized array object.</returns>
protected virtual object ReadArray(object reuse, ArraySchema writerSchema, Schema readerSchema, Decoder d)
{
ArraySchema rs = (ArraySchema)readerSchema;
object result = CreateArray(reuse, rs);
int i = 0;
for (int n = (int)d.ReadArrayStart(); n != 0; n = (int)d.ReadArrayNext())
{
if (GetArraySize(result) < (i + n)) ResizeArray(ref result, i + n);
for (int j = 0; j < n; j++, i++)
{
SetArrayElement(result, i, Read(GetArrayElement(result, i), writerSchema.ItemSchema, rs.ItemSchema, d));
}
}
if (GetArraySize(result) != i) ResizeArray(ref result, i);
return result;
}
/// <summary>
/// Creates a new array object. The initial size of the object could be anything. The users
/// should use GetArraySize() to determine the size. The default implementation creates an <c>object[]</c>.
/// </summary>
/// <param name="reuse">If appropriate use this instead of creating a new one.</param>
/// <returns>An object suitable to deserialize an avro array</returns>
protected virtual object CreateArray(object reuse, ArraySchema rs)
{
return (reuse != null && reuse is object[]) ? (object[])reuse : new object[0];
}
/// <summary>
/// Returns the size of the given array object.
/// </summary>
/// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by
/// a previous call to CreateArray().</param>
/// <returns>The size of the array</returns>
protected virtual int GetArraySize(object array)
{
return (array as object[]).Length;
}
/// <summary>
/// Resizes the array to the new value.
/// </summary>
/// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by
/// a previous call to CreateArray().</param>
/// <param name="n">The new size.</param>
protected virtual void ResizeArray(ref object array, int n)
{
object[] o = array as object[];
Array.Resize(ref o, n);
array = o;
}
/// <summary>
/// Assigns a new value to the object at the given index
/// </summary>
/// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by
/// a previous call to CreateArray().</param>
/// <param name="index">The index to reassign to.</param>
/// <param name="value">The value to assign.</param>
protected virtual void SetArrayElement(object array, int index, object value)
{
object[] a = array as object[];
a[index] = value;
}
/// <summary>
/// Returns the element at the given index.
/// </summary>
/// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by
/// a previous call to CreateArray().</param>
/// <param name="index">The index to look into.</param>
/// <returns>The object the given index. Null if no object has been assigned to that index.</returns>
protected virtual object GetArrayElement(object array, int index)
{
return (array as object[])[index];
}
/// <summary>
/// Deserialized an avro map. The default implemenation creats a new map using CreateMap() and then
/// adds elements to the map using AddMapEntry().
/// </summary>
/// <param name="reuse">If appropriate, use this instead of creating a new map object.</param>
/// <param name="writerSchema">The schema the writer used to write the map.</param>
/// <param name="readerSchema">The schema the reader is using.</param>
/// <param name="d">The decoder for serialization.</param>
/// <returns>The deserialized map object.</returns>
protected virtual object ReadMap(object reuse, MapSchema writerSchema, Schema readerSchema, Decoder d)
{
MapSchema rs = (MapSchema)readerSchema;
object result = CreateMap(reuse, rs);
for (int n = (int)d.ReadMapStart(); n != 0; n = (int)d.ReadMapNext())
{
for (int j = 0; j < n; j++)
{
string k = d.ReadString();
AddMapEntry(result, k, Read(null, writerSchema.ValueSchema, rs.ValueSchema, d));
}
}
return result;
}
/// <summary>
/// Used by the default implementation of ReadMap() to create a fresh map object. The default
/// implementaion of this method returns a IDictionary<string, map>.
/// </summary>
/// <param name="reuse">If appropriate, use this map object instead of creating a new one.</param>
/// <returns>An empty map object.</returns>
protected virtual object CreateMap(object reuse, MapSchema ms)
{
if (reuse != null && reuse is IDictionary<string, object>)
{
IDictionary<string, object> result = reuse as IDictionary<string, object>;
result.Clear();
return result;
}
return new Dictionary<string, object>();
}
/// <summary>
/// Adds an entry to the map.
/// </summary>
/// <param name="map">A map object, which is guaranteed to be one returned by a previous call to CreateMap().</param>
/// <param name="key">The key to add.</param>
/// <param name="value">The value to add.</param>
protected virtual void AddMapEntry(object map, string key, object value)
{
(map as IDictionary<string, object>).Add(key, value);
}
/// <summary>
/// Deserialized an object based on the writer's uninon schema.
/// </summary>
/// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param>
/// <param name="writerSchema">The UnionSchema that the writer used.</param>
/// <param name="readerSchema">The schema the reader uses.</param>
/// <param name="d">The decoder for serialization.</param>
/// <returns>The deserialized object.</returns>
protected virtual object ReadUnion(object reuse, UnionSchema writerSchema, Schema readerSchema, Decoder d)
{
int index = d.ReadUnionIndex();
Schema ws = writerSchema[index];
if (readerSchema is UnionSchema)
readerSchema = findBranch(readerSchema as UnionSchema, ws);
else
if (!readerSchema.CanRead(ws))
throw new AvroException("Schema mismatch. Reader: " + ReaderSchema + ", writer: " + WriterSchema);
return Read(reuse, ws, readerSchema, d);
}
/// <summary>
/// Deserializes a fixed object and returns the object. The default implementation uses CreateFixed()
/// and GetFixedBuffer() and returns what CreateFixed() returned.
/// </summary>
/// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param>
/// <param name="writerSchema">The FixedSchema the writer used during serialization.</param>
/// <param name="readerSchema">The schema that the readr uses. Must be a FixedSchema with the same
/// size as the writerSchema.</param>
/// <param name="d">The decoder for deserialization.</param>
/// <returns>The deserilized object.</returns>
protected virtual object ReadFixed(object reuse, FixedSchema writerSchema, Schema readerSchema, Decoder d)
{
FixedSchema rs = (FixedSchema)readerSchema;
if (rs.Size != writerSchema.Size)
{
throw new AvroException("Size mismatch between reader and writer fixed schemas. Writer: " + writerSchema +
", reader: " + readerSchema);
}
object ru = CreateFixed(reuse, rs);
byte[] bb = GetFixedBuffer(ru);
d.ReadFixed(bb);
return ru;
}
/// <summary>
/// Returns a fixed object.
/// </summary>
/// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param>
/// <param name="rs">The reader's FixedSchema.</param>
/// <returns>A fixed object with an appropriate buffer.</returns>
protected virtual object CreateFixed(object reuse, FixedSchema rs)
{
return (reuse != null && reuse is GenericFixed && (reuse as GenericFixed).Schema.Equals(rs)) ?
(GenericFixed)reuse : new GenericFixed(rs);
}
/// <summary>
/// Returns a buffer of appropriate size to read data into.
/// </summary>
/// <param name="f">The fixed object. It is guaranteed that this is something that has been previously
/// returned by CreateFixed</param>
/// <returns>A byte buffer of fixed's size.</returns>
protected virtual byte[] GetFixedBuffer(object f)
{
return (f as GenericFixed).Value;
}
protected virtual void Skip(Schema writerSchema, Decoder d)
{
switch (writerSchema.Tag)
{
case Schema.Type.Null:
d.SkipNull();
break;
case Schema.Type.Boolean:
d.SkipBoolean();
break;
case Schema.Type.Int:
d.SkipInt();
break;
case Schema.Type.Long:
d.SkipLong();
break;
case Schema.Type.Float:
d.SkipFloat();
break;
case Schema.Type.Double:
d.SkipDouble();
break;
case Schema.Type.String:
d.SkipString();
break;
case Schema.Type.Bytes:
d.SkipBytes();
break;
case Schema.Type.Record:
foreach (Field f in writerSchema as RecordSchema) Skip(f.Schema, d);
break;
case Schema.Type.Enumeration:
d.SkipEnum();
break;
case Schema.Type.Fixed:
d.SkipFixed((writerSchema as FixedSchema).Size);
break;
case Schema.Type.Array:
{
Schema s = (writerSchema as ArraySchema).ItemSchema;
for (long n = d.ReadArrayStart(); n != 0; n = d.ReadArrayNext())
{
for (long i = 0; i < n; i++) Skip(s, d);
}
}
break;
case Schema.Type.Map:
{
Schema s = (writerSchema as MapSchema).ValueSchema;
for (long n = d.ReadMapStart(); n != 0; n = d.ReadMapNext())
{
for (long i = 0; i < n; i++) { d.SkipString(); Skip(s, d); }
}
}
break;
case Schema.Type.Union:
Skip((writerSchema as UnionSchema)[d.ReadUnionIndex()], d);
break;
default:
throw new AvroException("Unknown schema type: " + writerSchema);
}
}
protected static Schema findBranch(UnionSchema us, Schema s)
{
int index = us.MatchingBranch(s);
if (index >= 0) return us[index];
throw new AvroException("No matching schema for " + s + " in " + us);
}
}
}
| |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CuttingEdge.Conditions.UnitTests.NumericTests
{
[TestClass]
public partial class NumericDoubleTests
{
[TestMethod]
[Description("Calling IsNaN on Double x with x is not a number should succeed.")]
public void IsDoubleNaNTest01()
{
Double a = Double.NaN;
Condition.Requires(a).IsNaN();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNaN on Double x with x is a number should fail.")]
public void IsDoubleNaNTest02()
{
Double a = 4;
Condition.Requires(a).IsNaN();
}
[TestMethod]
[Description("Calling IsNaN on Double x with x not a number and conditionDescription should pass.")]
public void IsDoubleNaNTest03()
{
Double a = Double.NaN;
Condition.Requires(a).IsNaN(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNaN on Double x with x a number and conditionDescription should fail.")]
public void IsDoubleNaNTest04()
{
Double a = 4;
Condition.Requires(a).IsNaN(string.Empty);
}
[TestMethod]
[Description("Calling IsNaN on Double x should succeed when exceptions are suppressed.")]
public void IsDoubleNaNTest05()
{
Double a = 4;
Condition.Requires(a).SuppressExceptionsForTest().IsNaN();
}
[TestMethod]
[Description("Calling IsNotNaN on Double x with x is a number should succeed.")]
public void IsDoubleNonNaNTest01()
{
Double a = 4;
Condition.Requires(a).IsNotNaN();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotNaN on Double x with x is not a number should fail.")]
public void IsDoubleNonNaNTest02()
{
Double a = Double.NaN;
Condition.Requires(a).IsNotNaN();
}
[TestMethod]
[Description("Calling IsNotNaN on Double x with x a number and conditionDescription should pass.")]
public void IsDoubleNonNaNTest03()
{
Double a = 4;
Condition.Requires(a).IsNotNaN(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotNaN on Double x with x not a number and conditionDescription should fail.")]
public void IsDoubleNonNaNTest04()
{
Double a = Double.NaN;
Condition.Requires(a).IsNotNaN(string.Empty);
}
[TestMethod]
[Description("Calling IsNotNaN on Double x should succeed when exceptions are suppressed.")]
public void IsDoubleNotNaNTest05()
{
Double a = Double.NaN;
Condition.Requires(a).SuppressExceptionsForTest().IsNotNaN();
}
[TestMethod]
[Description("Calling IsInfinity on Double x with x is negative infinity should succeed.")]
public void IsDoubleInfinityTest01()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsInfinity();
}
[TestMethod]
[Description("Calling IsInfinity on Double x with x is possitive infinity should succeed.")]
public void IsDoubleInfinityTest02()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsInfinity on Double x with x is a number should fail.")]
public void IsDoubleInfinityTest03()
{
Double a = 4;
Condition.Requires(a).IsInfinity();
}
[TestMethod]
[Description("Calling IsInfinity on Double x with x positive infinity and conditionDescription should pass.")]
public void IsDoubleInfinityTest04()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsInfinity(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsInfinity on Double x with x a number and conditionDescription should fail.")]
public void IsDoubleInfinityTest05()
{
Double a = 4;
Condition.Requires(a).IsInfinity(string.Empty);
}
[TestMethod]
[Description("Calling IsInfinity on Double x should succeed when exceptions are suppressed.")]
public void IsDoubleInfinityTest06()
{
Double a = 4;
Condition.Requires(a).SuppressExceptionsForTest().IsInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotInfinity on Double x with x is negative infinity should fail.")]
public void IsDoubleNotInfinityTest01()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsNotInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotInfinity on Double x with x is possitive infinity should fail.")]
public void IsDoubleNotInfinityTest02()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsNotInfinity();
}
[TestMethod]
[Description("Calling IsNotInfinity on Double x with x is a number should succeed.")]
public void IsDoubleNotInfinityTest03()
{
Double a = 4;
Condition.Requires(a).IsNotInfinity();
}
[TestMethod]
[Description("Calling IsNotInfinity on Double x with x a number and conditionDescription should pass.")]
public void IsDoubleNotInfinityTest04()
{
Double a = 4;
Condition.Requires(a).IsNotInfinity(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotInfinity on Double x with x positive infinity and conditionDescription should fail.")]
public void IsDoubleNotInfinityTest05()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsNotInfinity(string.Empty);
}
[TestMethod]
[Description("Calling IsNotInfinity on Double x should succeed when exceptions are suppressed.")]
public void IsDoubleNotInfinityTest06()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).SuppressExceptionsForTest().IsNotInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsPositiveInfinity on Double x with x is negative infinity should fail.")]
public void IsDoublePositiveInfinityTest01()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsPositiveInfinity();
}
[TestMethod]
[Description("Calling IsPositiveInfinity on Double x with x is possitive infinity should succeed.")]
public void IsDoublePositiveInfinityTest02()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsPositiveInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsPositiveInfinity on Double x with x is a number should fail.")]
public void IsDoublePositiveInfinityTest03()
{
Double a = 4;
Condition.Requires(a).IsPositiveInfinity();
}
[TestMethod]
[Description("Calling IsPositiveInfinity on Double x with x positive infinity and conditionDescription should pass.")]
public void IsDoublePositiveInfinityTest04()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsPositiveInfinity(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsPositiveInfinity on Double x with x negative infinity and conditionDescription should fail.")]
public void IsDoublePositiveInfinityTest05()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsPositiveInfinity(string.Empty);
}
[TestMethod]
[Description("Calling IsPositiveInfinity on Double x should succeed when exceptions are suppressed.")]
public void IsDoublePositiveInfinityTest06()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).SuppressExceptionsForTest().IsPositiveInfinity();
}
[TestMethod]
[Description("Calling IsNotPositiveInfinity on Double x with x is negative infinity should succeed.")]
public void IsDoubleNotPositiveInfinityTest01()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsNotPositiveInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotPositiveInfinity on Double x with x is possitive infinity should fail.")]
public void IsDoubleNotPositiveInfinityTest02()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsNotPositiveInfinity();
}
[TestMethod]
[Description("Calling IsNotPositiveInfinity on Double x with x is a number should succeed.")]
public void IsDoubleNotPositiveInfinityTest03()
{
Double a = 4;
Condition.Requires(a).IsNotPositiveInfinity();
}
[TestMethod]
[Description("Calling IsNotPositiveInfinity on Double x with x a number and conditionDescription should pass.")]
public void IsDoubleNotPositiveInfinityTest04()
{
Double a = 4;
Condition.Requires(a).IsNotPositiveInfinity(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotPositiveInfinity on Double x with positive infinity and conditionDescription should fail.")]
public void IsDoubleNotPositiveInfinityTest05()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsNotPositiveInfinity(string.Empty);
}
[TestMethod]
[Description("Calling IsNotPositiveInfinity on Double x should succeed when exceptions are suppressed.")]
public void IsDoubleNotPositiveInfinityTest06()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).SuppressExceptionsForTest().IsNotPositiveInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNegativeInfinity on Double x with x is positive infinity should fail.")]
public void IsDoubleNegativeInfinityTest01()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsNegativeInfinity();
}
[TestMethod]
[Description("Calling IsNegativeInfinity on Double x with x is negative infinity should succeed.")]
public void IsDoubleNegativeInfinityTest02()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsNegativeInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNegativeInfinity on Double x with x is a number should fail.")]
public void IsDoubleNegativeInfinityTest03()
{
Double a = 4;
Condition.Requires(a).IsNegativeInfinity();
}
[TestMethod]
[Description("Calling IsNegativeInfinity on Double x with x negative infinitiy and conditionDescription should pass.")]
public void IsDoubleNegativeInfinityTest04()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsNegativeInfinity(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNegativeInfinity on Double x with x positive infinity and conditionDescription should fail.")]
public void IsDoubleNegativeInfinityTest05()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsNegativeInfinity(string.Empty);
}
[TestMethod]
[Description("Calling IsNegativeInfinity on Double x should succeed when exceptions are suppressed.")]
public void IsDoubleNegativeInfinityTest06()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).SuppressExceptionsForTest().IsNegativeInfinity();
}
[TestMethod]
[Description("Calling IsNotNegativeInfinity on Double x with x is positive infinity should succeed.")]
public void IsDoubleNotNegativeInfinityTest01()
{
Double a = Double.PositiveInfinity;
Condition.Requires(a).IsNotNegativeInfinity();
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotNegativeInfinity on Double x with x is negative infinity should fail.")]
public void IsDoubleNotNegativeInfinityTest02()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsNotNegativeInfinity();
}
[TestMethod]
[Description("Calling IsNotNegativeInfinity on Double x with x is a number should succeed.")]
public void IsDoubleNotNegativeInfinityTest03()
{
Double a = 4;
Condition.Requires(a).IsNotNegativeInfinity();
}
[TestMethod]
[Description("Calling IsNotNegativeInfinity on Double x with x a number and conditionDescription should pass.")]
public void IsDoubleNotNegativeInfinityTest04()
{
Double a = 4;
Condition.Requires(a).IsNotNegativeInfinity(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Description("Calling IsNotNegativeInfinity on Double x with x negative infinity and conditionDescription should fail.")]
public void IsDoubleNotNegativeInfinityTest05()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).IsNotNegativeInfinity(string.Empty);
}
[TestMethod]
[Description("Calling IsNotNegativeInfinity on Double x should succeed when exceptions are suppressed.")]
public void IsDoubleNotNegativeInfinityTest06()
{
Double a = Double.NegativeInfinity;
Condition.Requires(a).SuppressExceptionsForTest().IsNotNegativeInfinity();
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
namespace System.Text.Html
{
/// <summary>
/// HtmlStringReader
/// </summary>
public class HtmlStringReader : IDisposable
{
private string _text;
private int _textLength;
private StringBuilder _b;
private int _startIndex = 0;
private int _valueStartIndex;
private int _valueEndIndex;
private int _openIndex = -1;
private int _closeIndex;
private string _lastParseElementName;
/// <summary>
/// Initializes a new instance of the <see cref="HtmlAdvancingTextProcess"/> class.
/// </summary>
/// <param name="text">The text.</param>
public HtmlStringReader(string text)
: this(text, new StringBuilder()) { }
/// <summary>
/// Initializes a new instance of the <see cref="HtmlAdvancingTextProcess"/> class.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="textBuilder">The text builder.</param>
public HtmlStringReader(string text, StringBuilder b)
{
_text = text;
_textLength = text.Length;
_b = b;
}
/// <summary>
/// Appends the specified value.
/// </summary>
/// <param name="value">The value.</param>
public void Append(string value)
{
_b.Append(value);
}
/// <summary>
/// Gets the found element.
/// </summary>
/// <returns></returns>
public string GetFoundElement()
{
if (_openIndex == -1)
throw new InvalidOperationException();
// find matching > to the open anchor tag
int openCloseBraceIndex = _text.IndexOf(">", _openIndex);
if (openCloseBraceIndex == -1)
openCloseBraceIndex = _textLength;
// extract tag
return _text.Substring(_openIndex, openCloseBraceIndex - _openIndex) + ">";
}
/// <summary>
/// Determines whether [is attribute in element] [the specified element].
/// </summary>
/// <param name="element">The element.</param>
/// <param name="attribute">The attribute.</param>
/// <returns>
/// <c>true</c> if [is attribute in element] [the specified element]; otherwise, <c>false</c>.
/// </returns>
public bool IsAttributeInElement(string element, string attribute)
{
int attributeLength = attribute.Length;
int targetStartKey = 0;
// if the tag contains the text "attribute"
int targetAttribIndex;
while ((targetAttribIndex = element.IndexOf(attribute, targetStartKey, StringComparison.OrdinalIgnoreCase)) > -1)
// determine whether "attribute" is inside of a string
if (((element.Substring(0, targetAttribIndex).Length - element.Substring(0, targetAttribIndex).Replace("\"", string.Empty).Length) % 2) == 0)
// "attribute" is not inside of a string -- attribute exists
return true;
else
// skip "attribute" text and look for next match
targetStartKey = targetAttribIndex + attributeLength;
return false;
}
/// <summary>
/// Indexes the of.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public int IndexOf(string value)
{
return _text.IndexOf(value, _startIndex, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Sets the search value.
/// </summary>
/// <param name="valueStartIndex">Start index of the value.</param>
/// <param name="valueEndIndex">End index of the value.</param>
public void SetSearchValue(int valueStartIndex, int valueEndIndex)
{
_valueStartIndex = valueStartIndex;
_valueEndIndex = valueEndIndex;
}
/// <summary>
/// Searches for any element.
/// </summary>
/// <returns></returns>
public bool SearchIfInElement()
{
_lastParseElementName = null;
// look for the closest open tag (<) to the left of the url
_openIndex = _text.LastIndexOf("<", _valueStartIndex, _valueStartIndex - _startIndex + 1, StringComparison.OrdinalIgnoreCase);
// open tag found
if (_openIndex > -1)
{
// find the corresponding close tag ([</][/>]) to the left of the url
_closeIndex = _text.LastIndexOf("</", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase);
int close2Index = _text.LastIndexOf("/>", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase);
if ((close2Index > -1) && (close2Index < _closeIndex))
_closeIndex = close2Index;
// false:close tag found -- url is not enclosed in an anchor tag
// true:close tag not found -- url is already linked (enclosed in an anchor tag)
return (_closeIndex == -1);
}
// open tag not found
else
return false;
}
/// <summary>
/// Searches for element.
/// </summary>
/// <param name="elementName">Name of the element.</param>
/// <returns></returns>
public bool SearchIfInElement(string elementName)
{
_lastParseElementName = elementName.ToLowerInvariant();
// look for the closest open element tag (<a>) to the left of the url
_openIndex = _text.LastIndexOf("<" + elementName + " ", _valueStartIndex, _valueStartIndex - _startIndex + 1, StringComparison.OrdinalIgnoreCase);
// open tag found
if (_openIndex > -1)
{
// find the corresponding close tag (</a>) to the left of the url
_closeIndex = _text.LastIndexOf("</" + elementName + ">", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase);
// false:close tag found -- value is not enclosed in an element tag
// true:close tag not found -- value is already elemented (enclosed in an anchor tag)
return (_closeIndex == -1);
}
// open tag not found
else
return false;
}
#region Stream
/// <summary>
/// Streams to end of first element.
/// </summary>
public void StreamToEndOfFirstElement()
{
// find the close tag (>) to the left of the url
int closeIndex = _text.IndexOf(">", _valueEndIndex, StringComparison.OrdinalIgnoreCase);
if (closeIndex > -1)
{
_b.Append(_text.Substring(_startIndex, closeIndex - _startIndex + 1));
Advance(closeIndex + 1);
}
else
{
_b.Append(_text.Substring(_startIndex));
Advance(_textLength);
}
}
/// <summary>
/// Streams the found element fragment.
/// </summary>
/// <param name="elementBuilder">The element builder.</param>
public void StreamFoundElementFragment(Func<string, string> elementBuilder)
{
if (_openIndex == -1)
throw new InvalidOperationException();
int elementOffset = _lastParseElementName.Length + 2;
// look for closing anchor tag
int closeIndex = _text.IndexOf("</" + _lastParseElementName + ">", _valueEndIndex, StringComparison.OrdinalIgnoreCase);
// close anchor tag found
if (closeIndex > -1)
{
closeIndex += elementOffset;
_b.Append(elementBuilder("<" + _lastParseElementName + " " + _text.Substring(_openIndex + elementOffset, closeIndex - _openIndex - elementOffset - 1)));
Advance(closeIndex + 1);
}
// close anchor tag not found
else
{
Advance(_textLength);
_b.Append(elementBuilder("<" + _lastParseElementName + " " + _text.Substring(_openIndex + elementOffset, _startIndex - _openIndex - elementOffset)));
}
}
/// <summary>
/// Streams to end of value.
/// </summary>
public void StreamToEndOfValue()
{
_b.Append(_text.Substring(_startIndex, _valueStartIndex - _startIndex));
Advance(_valueEndIndex + 1);
}
/// <summary>
/// Advances the specified index.
/// </summary>
/// <param name="index">The index.</param>
protected void Advance(int index)
{
_startIndex = index;
_openIndex = -1;
}
/// <summary>
/// Streams to begin element.
/// </summary>
public void StreamToBeginElement()
{
if (_openIndex == -1)
throw new InvalidOperationException();
// stream text to left of url
_b.Append(_text.Substring(_startIndex, _openIndex - _startIndex));
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
// append trailing text, if any
if (_startIndex < _textLength)
{
_b.Append(_text.Substring(_startIndex));
Advance(_textLength);
}
return _b.ToString();
}
#endregion
public void Dispose()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace RCube
{
public partial class MainForm : Form
{
private static int Distance = 50;
private static Color EmptySideColor = Color.Gray;
private static string[] SideNames = { "Top", "Front", "Left", "Down", "Back", "Right" };
private static Matrix UpPerspectiveRotation;
private static Matrix DownPerspectiveRotation;
private static string RotationChars = "urfdlb";
private static double[] cdfTable = { 0, 0.05, 0.1, 0.2, 0.33, 0.5, 0.66, 0.8, 0.9, 0.95, 1.0 };
private enum RotationCommand : int
{
None = -1,
Up = 0,
Right,
Front,
Down,
Left,
Back
}
static MainForm()
{
double pi2 = Math.PI / 2;
double pi4 = Math.PI / 4;
UpPerspectiveRotation = Transform3D.GetXRotation(-pi4) *
Transform3D.GetYRotation(Math.PI + pi4) * Transform3D.GetXRotation(pi2);
DownPerspectiveRotation = Transform3D.GetXRotation(pi4) *
Transform3D.GetYRotation(Math.PI + pi4) * Transform3D.GetXRotation(pi2);
}
private int[,] colors = new int[6, 9];
private int[,] colorsEntered;
private Color[] currentPalette = ChangePaletteForm.DefaultPalette;
public Color[] CurrentPalette
{
get { return currentPalette; }
}
private int selectedColor = 0;
private Matrix rotation = Transform3D.NoRotation;
private ScreenCubeDraw draw = null;
private PieceBounds[] pieces = null;
private int? side = null;
private double sideAngle = 0;
private int lastX;
private int lastY;
private bool isMoving = false;
private bool cancelClick = false;
private SolutionViewForm solutionView = null;
public MainForm()
{
InitializeComponent();
}
private Matrix GetTransformFor(int frontSide, bool downPerspective)
{
double pi2 = Math.PI / 2;
double pi4 = Math.PI / 4;
double angle = GetRotationAngleForFront(frontSide);
return Transform3D.GetXRotation(downPerspective ? pi4 : -pi4) *
Transform3D.GetYRotation(angle) * Transform3D.GetXRotation(pi2);
}
private Matrix GetTransformForRotation(int fromSide, int toSide, double position, bool downPerspective)
{
double pi2 = Math.PI / 2;
double pi4 = Math.PI / 4;
double angle = GetRotationAngleForFront(fromSide);
double angle2 = GetRotationAngleForFront(toSide);
// assert: max difference 1.5 * PI
if (Math.Abs(angle2 - angle) > Math.PI)
{
if (angle2 < angle) angle2 += 2 * Math.PI; else angle += 2 * Math.PI;
}
return Transform3D.GetXRotation(downPerspective ? pi4 : -pi4) *
Transform3D.GetYRotation(angle + (angle2 - angle) * position) * Transform3D.GetXRotation(pi2);
}
private double GetRotationAngleForFront(int frontSide)
{
double pi4 = Math.PI / 4;
switch (frontSide)
{
case 1:
return Math.PI + pi4;
case 2:
return Math.PI - pi4;
case 4:
return pi4;
case 5:
return -pi4;
default:
return 0;
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (side.HasValue)
draw.DrawRotation(e.Graphics, new RectangleF(0, 0, cube3DPictureBox.Width, cube3DPictureBox.Height), rotation, side.Value, sideAngle);
else
pieces = draw.Draw(e.Graphics, new RectangleF(0, 0, cube3DPictureBox.Width, cube3DPictureBox.Height), rotation);
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
lastX = e.X;
lastY = e.Y;
isMoving = true;
cancelClick = false;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isMoving)
{
double dX = Math.Atan2(e.X - cube3DPictureBox.Width / 2.0, Distance) - Math.Atan2(lastX - cube3DPictureBox.Width / 2.0, Distance);
double dY = Math.Atan2(e.Y - cube3DPictureBox.Height / 2.0, Distance) - Math.Atan2(lastY - cube3DPictureBox.Height / 2.0, Distance);
if (dX != 0)
{
rotation = Transform3D.GetYRotation(-dX) * rotation;
}
if (dY != 0)
{
rotation = Transform3D.GetXRotation(-dY) * rotation;
}
lastX = e.X;
lastY = e.Y;
cube3DPictureBox.Invalidate();
cancelClick = true;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
isMoving = false;
}
private void Form2_Load(object sender, EventArgs e)
{
draw = new ScreenCubeDraw(this);
if (Properties.Settings.Default.FirstRun)
{
Properties.Settings.Default.FirstRun = false;
Properties.Settings.Default.Save();
if (MessageBox.Show("Do you want to start demo?\nSame can be done by full cube creation, by mixing it, and by auto-solving.", "First time run", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
fullToolStripMenuItem_Click(this, EventArgs.Empty);
UpdateColorToolStrip();
mixToolStripMenuItem_Click(this, EventArgs.Empty);
solveToolStripMenuItem_Click(this, EventArgs.Empty);
return;
}
}
if (Properties.Settings.Default.LastCube != "")
{
string[] s = Properties.Settings.Default.LastCube.Split(' ');
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 9; j++)
{
colors[i, j] = int.Parse(s[i * 9 + j]);
}
}
}
colorsEntered = (int[,])colors.Clone();
UpdateColorToolStrip();
}
private void UpdateColorToolStrip()
{
int q = 0;
foreach (ToolStripButton btn in colorToolStrip.Items)
{
btn.Image = GetColorButton(CurrentPalette[q]);
btn.Text = CurrentPalette[q].Name;
btn.ToolTipText = String.Format("{1} ({0})", CurrentPalette[q].Name, SideNames[q]);
q++;
}
}
private Bitmap GetColorButton(Color color)
{
Bitmap bmp = new Bitmap(24, 24, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
g.FillEllipse(new SolidBrush(color), 0, 0, 23, 23);
}
return bmp;
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
if (cancelClick) return;
foreach (PieceBounds piece in pieces)
{
if (piece.InPiece(e.X, e.Y) && selectedColor > 0)
{
if (colorsEntered == null) colorsEntered = colors;
colorsEntered[piece.Side, piece.Piece] = selectedColor;
DoColorsInput();
cube3DPictureBox.Invalidate();
}
}
}
private void DoColorsInput()
{
if (autocompleteToolStripMenuItem.Checked)
{
colors = (int[,])colorsEntered.Clone();
try
{
ColorFinder.FindColors(colors);
}
catch
{
}
}
else
colors = colorsEntered;
}
private void Form2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '6')
{
SetSelectedColor(e.KeyChar - '0');
e.Handled = true;
}
else
{
int i = GetSideOfCommand(e.KeyChar);
bool reverse = Char.IsUpper(e.KeyChar);
if (i >= 0 && !moveWorker.IsBusy)
{
moveWorker.RunWorkerAsync((reverse ? ~i : i));
e.Handled = true;
}
}
}
private void DoRotationCommand(char command)
{
int i = GetSideOfCommand(command);
if (i >= 0 && !moveWorker.IsBusy)
{
moveWorker.RunWorkerAsync(i);
colorsEntered = null;
}
}
private int GetSideOfCommand(char command)
{
int commandIndex = RotationChars.IndexOf(Char.ToLower(command));
Dictionary<int, PointF> centers = new Dictionary<int, PointF>();
for (int i = 0; i < pieces.Length; i++)
{
if (pieces[i].Piece == 8)
{
PointF p = new PointF((pieces[i].Bounds[0].X + pieces[i].Bounds[2].X) / 2,
(pieces[i].Bounds[0].Y + pieces[i].Bounds[2].Y) / 2);
centers.Add(pieces[i].Side, p);
}
}
if (centers.Count != 3) return -1;
int[] sides = new int[3];
PointF[] centerPoints = new PointF[3];
int j = 0;
foreach (KeyValuePair<int, PointF> item in centers)
{
sides[j] = item.Key;
centerPoints[j] = item.Value;
j++;
}
Array.Sort<PointF, int>(centerPoints, sides, new PointFXComparer());
if (Math.Abs(Math.Atan2(centerPoints[2].Y - centerPoints[0].Y, centerPoints[2].X - centerPoints[0].X)) < Math.PI / 6)
{
bool upVisible = Math.Max(centerPoints[2].Y, centerPoints[0].Y) > centerPoints[1].Y;
int frontSide = sides[0];
int rightSide = sides[2];
int upSide = upVisible ? sides[1] : ((sides[1] + 3) % 6);
switch ((RotationCommand)commandIndex)
{
case RotationCommand.Front:
return frontSide;
case RotationCommand.Up:
return upSide;
case RotationCommand.Right:
return rightSide;
case RotationCommand.Back:
return (frontSide + 3) % 6;
case RotationCommand.Down:
return (upSide + 3) % 6;
case RotationCommand.Left:
return (rightSide + 3) % 6;
}
}
return -1;
}
private char GetCommandOfSide(int side, int downSide, int frontSide)
{
if (side == downSide)
return RotationChars[(int)RotationCommand.Down];
else if (side == frontSide)
return RotationChars[(int)RotationCommand.Front];
else if (side == (downSide + 3) % 6)
return RotationChars[(int)RotationCommand.Up];
else if (side == (frontSide + 3) % 6)
return RotationChars[(int)RotationCommand.Back];
else
{
int rightSide = Cube.RightSideForUpAndFront[(downSide + 3) % 6, frontSide];
if (side == rightSide)
return RotationChars[(int)RotationCommand.Right];
else
return RotationChars[(int)RotationCommand.Left];
}
}
private void RotateSide(int side, bool reverse)
{
int[][,] rotations = Cube.GetRotations(side);
for (int j = 0; j < 5; j++)
{
if (!reverse)
{
int t = colors[rotations[j][0, 3], rotations[j][1, 3]];
for (int q = 3; q > 0; q--)
{
colors[rotations[j][0, q], rotations[j][1, q]] =
colors[rotations[j][0, q - 1], rotations[j][1, q - 1]];
}
colors[rotations[j][0, 0], rotations[j][1, 0]] = t;
}
else
{
int t = colors[rotations[j][0, 0], rotations[j][1, 0]];
for (int q = 1; q < 4; q++)
{
colors[rotations[j][0, q - 1], rotations[j][1, q - 1]] =
colors[rotations[j][0, q], rotations[j][1, q]];
}
colors[rotations[j][0, 3], rotations[j][1, 3]] = t;
}
}
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
string[] s = new string[6 * 9];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 9; j++)
{
s[i * 9 + j] = colors[i, j].ToString();
}
}
Properties.Settings.Default.LastCube = String.Join(" ", s);
Properties.Settings.Default.Save();
}
private void pictureBox1_Resize(object sender, EventArgs e)
{
cube3DPictureBox.Invalidate();
}
private void frontToolStripMenuItem_Click(object sender, EventArgs e)
{
DoRotationCommand((sender as ToolStripMenuItem).ShortcutKeyDisplayString[0]);
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
colorsEntered = new int[6, 9];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 9; j++)
{
colorsEntered[i, j] = 0;
}
}
DoColorsInput();
cube3DPictureBox.Invalidate();
}
private void baseToolStripMenuItem_Click(object sender, EventArgs e)
{
colorsEntered = new int[6, 9];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 8; j++)
{
colorsEntered[i, j] = 0;
}
colorsEntered[i, 8] = i + 1;
}
DoColorsInput();
cube3DPictureBox.Invalidate();
}
private void fullToolStripMenuItem_Click(object sender, EventArgs e)
{
colorsEntered = new int[6, 9];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 9; j++)
{
colorsEntered[i, j] = i + 1;
}
}
DoColorsInput();
cube3DPictureBox.Invalidate();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void SetSelectedColor(int color)
{
for (int i = 0; i < colorToolStrip.Items.Count; i++)
{
(colorToolStrip.Items[i] as ToolStripButton).Checked = color == i + 1;
}
selectedColor = color;
}
private void colorToolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
int j = 0;
for (int i = 0; i < colorToolStrip.Items.Count; i++)
{
if (colorToolStrip.Items[i] == e.ClickedItem)
j = i + 1;
}
SetSelectedColor(selectedColor == j ? 0 : j);
}
private void autocompleteToolStripMenuItem_Click(object sender, EventArgs e)
{
DoColorsInput();
cube3DPictureBox.Invalidate();
}
private void mixToolStripMenuItem_Click(object sender, EventArgs e)
{
Random r = new Random();
for (int i = 0; i < 100; i++)
{
int side = r.Next(6);
bool reverse = r.NextDouble() >= 0.5;
RotateSide(side, reverse);
}
colorsEntered = null;
cube3DPictureBox.Invalidate();
}
private void solveToolStripMenuItem_Click(object sender, EventArgs e)
{
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 9; j++)
{
if (colors[i, j] == 0)
{
MessageBox.Show("Specify all colors");
return;
}
}
}
Color[] cubeColors = new Color[6];
int[] colorReverseMap = new int[6];
Dictionary<int, int> colorMap = new Dictionary<int, int>();
for (int i = 0; i < 6; i++)
{
colorMap.Add(colors[i, 8], i);
colorReverseMap[i] = colors[i, 8];
cubeColors[i] = CurrentPalette[colors[i, 8] - 1];
}
Cube c = new Cube(false);
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 8; j++)
{
c.Sides[i, j] = colorMap[colors[i, j]];
}
}
CubeSolver solver;
CubeSolutionGroup[] solutionGroups;
try
{
CubeSolverFactory solverFactory = new CubeSolverFactory();
solver = solverFactory.CreateCubeSolver();
solutionGroups = solver.Solve(c);
}
catch (Exception ex)
{
MessageBox.Show("Unable to find solution: " + ex.Message);
return;
}
if (solutionView == null)
{
solutionView = new SolutionViewForm();
solutionView.Disposed += new EventHandler(delegate
{
solutionView = null;
});
solutionView.Owner = this;
solutionView.Show();
if (this.Left > solutionView.Width)
solutionView.Left = this.Left - solutionView.Width + 10;
else if (Screen.PrimaryScreen.WorkingArea.Width - this.Right > solutionView.Width)
solutionView.Left = this.Right - 10;
}
solutionView.Clear();
for (int i = 0; i < solutionGroups.Length; i++)
{
SolutionViewCubeDraw drawIcon = new SolutionViewCubeDraw(solutionGroups[i].StartCube, CurrentPalette);
Bitmap bmp = new Bitmap(48, 48);
Graphics g = Graphics.FromImage(bmp);
drawIcon.Draw(g, new RectangleF(-8, -8, bmp.Width + 16, bmp.Height + 16),
GetTransformFor(solutionGroups[i].frontSide, solutionGroups[i].stage < 1));
g.Dispose();
StringBuilder sb = new StringBuilder();
for (int j = 0; j < solutionGroups[i].rotation.Length; j++)
{
int q = solutionGroups[i].rotation[j];
char cmd = GetCommandOfSide(q < 0 ? ~q : q, solver.BaseSide, solutionGroups[i].frontSide);
sb.Append(Char.ToUpper(cmd));
if (q < 0) sb.Append('\'');
sb.Append(' ');
}
solutionView.AddLine("", sb.ToString(), bmp);
}
EnableControl(false);
solutionWorker.RunWorkerAsync(solutionGroups);
}
private void EnableControl(bool enabled)
{
menuStrip1.Enabled = enabled;
colorToolStrip.Enabled = enabled;
}
private void frontToolStripMenuItem1_Click(object sender, EventArgs e)
{
rotation = Transform3D.NoRotation;
cube3DPictureBox.Invalidate();
}
private void upPerspectiveToolStripMenuItem_Click(object sender, EventArgs e)
{
rotation = UpPerspectiveRotation;
cube3DPictureBox.Invalidate();
}
private void downPerspectiveToolStripMenuItem_Click(object sender, EventArgs e)
{
rotation = DownPerspectiveRotation;
cube3DPictureBox.Invalidate();
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
CubeStorage loadedCube = CubeStorage.Load(openFileDialog1.FileName);
colorsEntered = new int[6, 9];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 9; j++)
{
colorsEntered[i, j] = loadedCube.SideColors[i][j];
}
}
if (loadedCube.Colors == null)
{
currentPalette = ChangePaletteForm.DefaultPalette;
}
else
{
Color[] palette = new Color[6];
for (int i = 0; i < palette.Length; i++)
{
palette[i] = Color.FromArgb(loadedCube.Colors[i]);
}
currentPalette = palette;
}
if (loadedCube.Rotation != null)
{
Matrix rotation = new Matrix(4, 4);
for (int i = 0; i < 16; i++)
{
rotation[i / 4, i % 4] = loadedCube.Rotation[i];
}
this.rotation = rotation;
}
DoColorsInput();
UpdateColorToolStrip();
cube3DPictureBox.Invalidate();
}
catch
{
MessageBox.Show("Invalid data file");
}
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
CubeStorage cubeToStore = new CubeStorage();
cubeToStore.SideColors = new int[6][];
for (int i = 0; i < 6; i++)
{
cubeToStore.SideColors[i] = new int[9];
for (int j = 0; j < 9; j++)
{
cubeToStore.SideColors[i][j] = colors[i, j];
}
}
cubeToStore.Colors = new int[6];
for (int i = 0; i < 6; i++)
{
cubeToStore.Colors[i] = CurrentPalette[i].ToArgb();
}
cubeToStore.Rotation = new double[16];
for (int i = 0; i < 16; i++)
{
cubeToStore.Rotation[i] = rotation[i / 4, i % 4];
}
cubeToStore.Save(saveFileDialog1.FileName);
}
}
private double AproximateMovementPosition(int i, int total)
{
// simple: return (double)i / total;
double value = (double)i * (cdfTable.Length - 1) / total;
int low = (int)Math.Floor(value);
int high = (int)Math.Ceiling(value);
if (low == high) return cdfTable[low];
return cdfTable[low] + (cdfTable[high] - cdfTable[low]) * (value - low) / (high - low);
}
private void moveWorker_DoWork(object sender, DoWorkEventArgs e)
{
int i = (int)e.Argument;
bool reverse = false;
if (i < 0) { i = ~i; reverse = true; }
side = i;
int steps = 6;
for (int j = 0; j < steps; j++)
{
sideAngle = Math.PI / 2 * AproximateMovementPosition(j, steps);
if (reverse) sideAngle = -sideAngle;
IAsyncResult r =
cube3DPictureBox.BeginInvoke(new CallbackDelegate(delegate { cube3DPictureBox.Refresh(); }));
System.Threading.Thread.Sleep(50);
cube3DPictureBox.EndInvoke(r);
}
side = null;
RotateSide(i, reverse);
cube3DPictureBox.Invalidate();
}
private void rotationWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (e.Argument is int)
{
Matrix baseRotation = rotation;
int steps = 5;
for (int j = 0; j <= steps; j++)
{
double alpha = Math.PI / 2 * AproximateMovementPosition(j, steps);
switch ((int)e.Argument)
{
case 0:
rotation = Transform3D.GetYRotation(-alpha) * baseRotation;
break;
case 1:
rotation = Transform3D.GetYRotation(alpha) * baseRotation;
break;
case 2:
rotation = Transform3D.GetXRotation(alpha) * baseRotation;
break;
case 3:
rotation = Transform3D.GetXRotation(-alpha) * baseRotation;
break;
}
IAsyncResult r =
cube3DPictureBox.BeginInvoke(new CallbackDelegate(delegate { cube3DPictureBox.Refresh(); }));
System.Threading.Thread.Sleep(50);
cube3DPictureBox.EndInvoke(r);
}
}
else if(e.Argument is FrontSideRotationTask)
{
FrontSideRotationTask task = (FrontSideRotationTask)e.Argument;
int steps = 9;
for (int j = 0; j <= steps; j++)
{
rotation = GetTransformForRotation(task.From, task.To,
AproximateMovementPosition(j, steps), task.DownView);
IAsyncResult r =
cube3DPictureBox.BeginInvoke(new CallbackDelegate(delegate { cube3DPictureBox.Refresh(); }));
System.Threading.Thread.Sleep(50);
cube3DPictureBox.EndInvoke(r);
}
}
}
private void rotateXXXToolStripMenuItem_Click(object sender, EventArgs e)
{
DoRotate(int.Parse(((ToolStripMenuItem)sender).Tag as string));
}
private void DoRotate(int command)
{
if (!rotationWorker.IsBusy)
rotationWorker.RunWorkerAsync(command);
}
protected override bool ProcessDialogKey(Keys keyData)
{
switch (keyData)
{
case Keys.Right:
DoRotate(0);
break;
case Keys.Left:
DoRotate(1);
break;
case Keys.Up:
DoRotate(2);
break;
case Keys.Down:
DoRotate(3);
break;
default:
return base.ProcessDialogKey(keyData);
}
return true;
}
private void solutionWorker_DoWork(object sender, DoWorkEventArgs e)
{
Color[] cubeColors = new Color[6];
int[] colorReverseMap = new int[6];
for (int i = 0; i < 6; i++)
{
colorReverseMap[i] = colors[i, 8];
}
CubeSolutionGroup[] sol = (CubeSolutionGroup[])e.Argument;
//Cube c = sol[sol.Length - 1].StartCube;
//for (int i = 0; i < 6; i++)
//{
// for (int j = 0; j < 8; j++)
// {
// colors[i, j] = colorReverseMap[c.Sides[i, j]];
// }
//}
//colorsEntered = null;
//pictureBox1.Invalidate();
rotation = DownPerspectiveRotation;
cube3DPictureBox.Invalidate();
int currentFront = 0;
bool downView = true;
for (int i = 0; i < sol.Length; i++)
{
CubeSolutionGroup grp = sol[i];
if (downView && grp.stage > 0)
{
rotationWorker.RunWorkerAsync(3);
while (rotationWorker.IsBusy)
{
System.Threading.Thread.Sleep(100);
}
downView = false;
}
if (currentFront != grp.frontSide)
{
rotationWorker.RunWorkerAsync(new FrontSideRotationTask(currentFront, grp.frontSide, downView));
while (rotationWorker.IsBusy)
{
System.Threading.Thread.Sleep(100);
}
currentFront = grp.frontSide;
}
for (int j = 0; j < grp.rotation.Length; j++)
{
moveWorker.RunWorkerAsync(grp.rotation[j]);
while (moveWorker.IsBusy)
{
System.Threading.Thread.Sleep(100);
}
}
}
}
private void captureToolStripMenuItem_Click(object sender, EventArgs e)
{
using (CaptureForm form = new CaptureForm())
{
if (form.ShowDialog() == DialogResult.OK)
{
int[] t = CubeSidesColorOffset.FindTransform(form.Colors);
Color[] palette = new Color[6];
for (int i = 0; i < palette.Length; i++)
{
palette[t[i]] = form.Colors[i];
}
currentPalette = palette;
int[,] data = new int[6, 9];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 9; j++)
{
data[t[i], j] = t[form.Cube[i, j]] + 1;
}
}
colorsEntered = data;
DoColorsInput();
UpdateColorToolStrip();
}
}
}
private void changePaletteMenuItem_Click(object sender, EventArgs e)
{
using (ChangePaletteForm form = new ChangePaletteForm())
{
if (form.ShowDialog() == DialogResult.OK)
{
}
}
}
delegate void CallbackDelegate();
private class ScreenCubeDraw : Cube2DDraw
{
private MainForm form;
public ScreenCubeDraw(MainForm form) { this.form = form; }
public override Color GetSidePieceColor(int side, int piece)
{
if (piece < 0 || form.colors[side, piece] == 0)
return EmptySideColor;
else
return form.CurrentPalette[form.colors[side, piece] - 1];
}
}
private class SolutionViewCubeDraw : Cube2DDraw
{
private Cube cube;
private Color[] palette;
public SolutionViewCubeDraw(Cube cube, Color[] palette)
{
this.cube = cube;
this.palette = palette;
}
public override Color GetSidePieceColor(int side, int piece)
{
if (piece < 0)
return EmptySideColor;
else if (piece < 8)
return palette[cube[side, piece]];
else
return palette[side];
}
}
private class PointFXComparer : IComparer<PointF>
{
public int Compare(PointF x, PointF y)
{
return Comparer<float>.Default.Compare(x.X, y.X);
}
}
private class FrontSideRotationTask
{
public int From;
public int To;
public bool DownView;
public FrontSideRotationTask(int from, int to, bool downView)
{
this.From = from;
this.To = to;
this.DownView = downView;
}
}
private void solutionWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
EnableControl(true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.DirectoryServices.Protocols
{
public partial class AddRequest : System.DirectoryServices.Protocols.DirectoryRequest
{
public AddRequest() { }
public AddRequest(string distinguishedName, params System.DirectoryServices.Protocols.DirectoryAttribute[] attributes) { }
public AddRequest(string distinguishedName, string objectClass) { }
public System.DirectoryServices.Protocols.DirectoryAttributeCollection Attributes { get { throw null; } }
public string DistinguishedName { get { throw null; } set { } }
}
public partial class AddResponse : System.DirectoryServices.Protocols.DirectoryResponse
{
internal AddResponse() { }
}
public partial class AsqRequestControl : System.DirectoryServices.Protocols.DirectoryControl
{
public AsqRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public AsqRequestControl(string attributeName) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public string AttributeName { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public partial class AsqResponseControl : System.DirectoryServices.Protocols.DirectoryControl
{
internal AsqResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } }
}
public enum AuthType
{
Anonymous = 0,
Basic = 1,
Negotiate = 2,
Ntlm = 3,
Digest = 4,
Sicily = 5,
Dpa = 6,
Msn = 7,
External = 8,
Kerberos = 9,
}
public partial class BerConversionException : System.DirectoryServices.Protocols.DirectoryException
{
public BerConversionException() { }
protected BerConversionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public BerConversionException(string message) { }
public BerConversionException(string message, System.Exception inner) { }
}
public static partial class BerConverter
{
public static object[] Decode(string format, byte[] value) { throw null; }
public static byte[] Encode(string format, params object[] value) { throw null; }
}
public partial class CompareRequest : System.DirectoryServices.Protocols.DirectoryRequest
{
public CompareRequest() { }
public CompareRequest(string distinguishedName, System.DirectoryServices.Protocols.DirectoryAttribute assertion) { }
public CompareRequest(string distinguishedName, string attributeName, byte[] value) { }
public CompareRequest(string distinguishedName, string attributeName, string value) { }
public CompareRequest(string distinguishedName, string attributeName, System.Uri value) { }
public System.DirectoryServices.Protocols.DirectoryAttribute Assertion { get { throw null; } }
public string DistinguishedName { get { throw null; } set { } }
}
public partial class CompareResponse : System.DirectoryServices.Protocols.DirectoryResponse
{
internal CompareResponse() { }
}
public partial class CrossDomainMoveControl : System.DirectoryServices.Protocols.DirectoryControl
{
public CrossDomainMoveControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public CrossDomainMoveControl(string targetDomainController) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public string TargetDomainController { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public partial class DeleteRequest : System.DirectoryServices.Protocols.DirectoryRequest
{
public DeleteRequest() { }
public DeleteRequest(string distinguishedName) { }
public string DistinguishedName { get { throw null; } set { } }
}
public partial class DeleteResponse : System.DirectoryServices.Protocols.DirectoryResponse
{
internal DeleteResponse() { }
}
public enum DereferenceAlias
{
Never = 0,
InSearching = 1,
FindingBaseObject = 2,
Always = 3,
}
public delegate void DereferenceConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection connectionToDereference);
public partial class DirectoryAttribute : System.Collections.CollectionBase
{
public DirectoryAttribute() { }
public DirectoryAttribute(string name, byte[] value) { }
public DirectoryAttribute(string name, params object[] values) { }
public DirectoryAttribute(string name, string value) { }
public DirectoryAttribute(string name, System.Uri value) { }
public object this[int index] { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
public int Add(byte[] value) { throw null; }
public int Add(string value) { throw null; }
public int Add(System.Uri value) { throw null; }
public void AddRange(object[] values) { }
public bool Contains(object value) { throw null; }
public void CopyTo(object[] array, int index) { }
public object[] GetValues(System.Type valuesType) { throw null; }
public int IndexOf(object value) { throw null; }
public void Insert(int index, byte[] value) { }
public void Insert(int index, string value) { }
public void Insert(int index, System.Uri value) { }
protected override void OnValidate(object value) { }
public void Remove(object value) { }
}
public partial class DirectoryAttributeCollection : System.Collections.CollectionBase
{
public DirectoryAttributeCollection() { }
public System.DirectoryServices.Protocols.DirectoryAttribute this[int index] { get { throw null; } set { } }
public int Add(System.DirectoryServices.Protocols.DirectoryAttribute attribute) { throw null; }
public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeCollection attributeCollection) { }
public void AddRange(System.DirectoryServices.Protocols.DirectoryAttribute[] attributes) { }
public bool Contains(System.DirectoryServices.Protocols.DirectoryAttribute value) { throw null; }
public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttribute[] array, int index) { }
public int IndexOf(System.DirectoryServices.Protocols.DirectoryAttribute value) { throw null; }
public void Insert(int index, System.DirectoryServices.Protocols.DirectoryAttribute value) { }
protected override void OnValidate(object value) { }
public void Remove(System.DirectoryServices.Protocols.DirectoryAttribute value) { }
}
public partial class DirectoryAttributeModification : System.DirectoryServices.Protocols.DirectoryAttribute
{
public DirectoryAttributeModification() { }
public System.DirectoryServices.Protocols.DirectoryAttributeOperation Operation { get { throw null; } set { } }
}
public partial class DirectoryAttributeModificationCollection : System.Collections.CollectionBase
{
public DirectoryAttributeModificationCollection() { }
public System.DirectoryServices.Protocols.DirectoryAttributeModification this[int index] { get { throw null; } set { } }
public int Add(System.DirectoryServices.Protocols.DirectoryAttributeModification attribute) { throw null; }
public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection attributeCollection) { }
public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeModification[] attributes) { }
public bool Contains(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { throw null; }
public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttributeModification[] array, int index) { }
public int IndexOf(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { throw null; }
public void Insert(int index, System.DirectoryServices.Protocols.DirectoryAttributeModification value) { }
protected override void OnValidate(object value) { }
public void Remove(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { }
}
public enum DirectoryAttributeOperation
{
Add = 0,
Delete = 1,
Replace = 2,
}
public abstract partial class DirectoryConnection
{
protected DirectoryConnection() { }
public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } }
public virtual System.Net.NetworkCredential Credential { set { } }
public virtual System.DirectoryServices.Protocols.DirectoryIdentifier Directory { get { throw null; } }
public virtual System.TimeSpan Timeout { get { throw null; } set { } }
public abstract System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request);
}
public partial class DirectoryControl
{
public DirectoryControl(string type, byte[] value, bool isCritical, bool serverSide) { }
public bool IsCritical { get { throw null; } set { } }
public bool ServerSide { get { throw null; } set { } }
public string Type { get { throw null; } }
public virtual byte[] GetValue() { throw null; }
}
public partial class DirectoryControlCollection : System.Collections.CollectionBase
{
public DirectoryControlCollection() { }
public System.DirectoryServices.Protocols.DirectoryControl this[int index] { get { throw null; } set { } }
public int Add(System.DirectoryServices.Protocols.DirectoryControl control) { throw null; }
public void AddRange(System.DirectoryServices.Protocols.DirectoryControlCollection controlCollection) { }
public void AddRange(System.DirectoryServices.Protocols.DirectoryControl[] controls) { }
public bool Contains(System.DirectoryServices.Protocols.DirectoryControl value) { throw null; }
public void CopyTo(System.DirectoryServices.Protocols.DirectoryControl[] array, int index) { }
public int IndexOf(System.DirectoryServices.Protocols.DirectoryControl value) { throw null; }
public void Insert(int index, System.DirectoryServices.Protocols.DirectoryControl value) { }
protected override void OnValidate(object value) { }
public void Remove(System.DirectoryServices.Protocols.DirectoryControl value) { }
}
public partial class DirectoryException : System.Exception
{
public DirectoryException() { }
protected DirectoryException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public DirectoryException(string message) { }
public DirectoryException(string message, System.Exception inner) { }
}
public abstract partial class DirectoryIdentifier
{
protected DirectoryIdentifier() { }
}
public partial class DirectoryNotificationControl : System.DirectoryServices.Protocols.DirectoryControl
{
public DirectoryNotificationControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
}
public abstract partial class DirectoryOperation
{
protected DirectoryOperation() { }
}
public partial class DirectoryOperationException : System.DirectoryServices.Protocols.DirectoryException, System.Runtime.Serialization.ISerializable
{
public DirectoryOperationException() { }
public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response) { }
public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message) { }
public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message, System.Exception inner) { }
protected DirectoryOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public DirectoryOperationException(string message) { }
public DirectoryOperationException(string message, System.Exception inner) { }
public System.DirectoryServices.Protocols.DirectoryResponse Response { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
}
public abstract partial class DirectoryRequest : System.DirectoryServices.Protocols.DirectoryOperation
{
internal DirectoryRequest() { }
public System.DirectoryServices.Protocols.DirectoryControlCollection Controls { get { throw null; } }
public string RequestId { get { throw null; } set { } }
}
public abstract partial class DirectoryResponse : System.DirectoryServices.Protocols.DirectoryOperation
{
internal DirectoryResponse() { }
public virtual System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } }
public virtual string ErrorMessage { get { throw null; } }
public virtual string MatchedDN { get { throw null; } }
public virtual System.Uri[] Referral { get { throw null; } }
public string RequestId { get { throw null; } }
public virtual System.DirectoryServices.Protocols.ResultCode ResultCode { get { throw null; } }
}
[System.FlagsAttribute]
public enum DirectorySynchronizationOptions : long
{
None = (long)0,
ObjectSecurity = (long)1,
ParentsFirst = (long)2048,
PublicDataOnly = (long)8192,
IncrementalValues = (long)2147483648,
}
public partial class DirSyncRequestControl : System.DirectoryServices.Protocols.DirectoryControl
{
public DirSyncRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public DirSyncRequestControl(byte[] cookie) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public DirSyncRequestControl(byte[] cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions option) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public DirSyncRequestControl(byte[] cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions option, int attributeCount) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public int AttributeCount { get { throw null; } set { } }
public byte[] Cookie { get { throw null; } set { } }
public System.DirectoryServices.Protocols.DirectorySynchronizationOptions Option { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public partial class DirSyncResponseControl : System.DirectoryServices.Protocols.DirectoryControl
{
internal DirSyncResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public byte[] Cookie { get { throw null; } }
public bool MoreData { get { throw null; } }
public int ResultSize { get { throw null; } }
}
public partial class DomainScopeControl : System.DirectoryServices.Protocols.DirectoryControl
{
public DomainScopeControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
}
public partial class DsmlAuthRequest : System.DirectoryServices.Protocols.DirectoryRequest
{
public DsmlAuthRequest() { }
public DsmlAuthRequest(string principal) { }
public string Principal { get { throw null; } set { } }
}
public partial class ExtendedDNControl : System.DirectoryServices.Protocols.DirectoryControl
{
public ExtendedDNControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public ExtendedDNControl(System.DirectoryServices.Protocols.ExtendedDNFlag flag) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public System.DirectoryServices.Protocols.ExtendedDNFlag Flag { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public enum ExtendedDNFlag
{
HexString = 0,
StandardString = 1,
}
public partial class ExtendedRequest : System.DirectoryServices.Protocols.DirectoryRequest
{
public ExtendedRequest() { }
public ExtendedRequest(string requestName) { }
public ExtendedRequest(string requestName, byte[] requestValue) { }
public string RequestName { get { throw null; } set { } }
public byte[] RequestValue { get { throw null; } set { } }
}
public partial class ExtendedResponse : System.DirectoryServices.Protocols.DirectoryResponse
{
internal ExtendedResponse() { }
public string ResponseName { get { throw null; } }
public byte[] ResponseValue { get { throw null; } }
}
public partial class LazyCommitControl : System.DirectoryServices.Protocols.DirectoryControl
{
public LazyCommitControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
}
public partial class LdapConnection : System.DirectoryServices.Protocols.DirectoryConnection, System.IDisposable
{
public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier) { }
public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential) { }
public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, System.DirectoryServices.Protocols.AuthType authType) { }
public LdapConnection(string server) { }
public System.DirectoryServices.Protocols.AuthType AuthType { get { throw null; } set { } }
public bool AutoBind { get { throw null; } set { } }
public override System.Net.NetworkCredential Credential { set { } }
public System.DirectoryServices.Protocols.LdapSessionOptions SessionOptions { get { throw null; } }
public override System.TimeSpan Timeout { get { throw null; } set { } }
public void Abort(System.IAsyncResult asyncResult) { }
public System.IAsyncResult BeginSendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.DirectoryServices.Protocols.PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { throw null; }
public System.IAsyncResult BeginSendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.TimeSpan requestTimeout, System.DirectoryServices.Protocols.PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { throw null; }
public void Bind() { }
public void Bind(System.Net.NetworkCredential newCredential) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.DirectoryServices.Protocols.DirectoryResponse EndSendRequest(System.IAsyncResult asyncResult) { throw null; }
~LdapConnection() { }
public System.DirectoryServices.Protocols.PartialResultsCollection GetPartialResults(System.IAsyncResult asyncResult) { throw null; }
public override System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request) { throw null; }
public System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.TimeSpan requestTimeout) { throw null; }
}
public partial class LdapDirectoryIdentifier : System.DirectoryServices.Protocols.DirectoryIdentifier
{
public LdapDirectoryIdentifier(string server) { }
public LdapDirectoryIdentifier(string server, bool fullyQualifiedDnsHostName, bool connectionless) { }
public LdapDirectoryIdentifier(string server, int portNumber) { }
public LdapDirectoryIdentifier(string server, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) { }
public LdapDirectoryIdentifier(string[] servers, bool fullyQualifiedDnsHostName, bool connectionless) { }
public LdapDirectoryIdentifier(string[] servers, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) { }
public bool Connectionless { get { throw null; } }
public bool FullyQualifiedDnsHostName { get { throw null; } }
public int PortNumber { get { throw null; } }
public string[] Servers { get { throw null; } }
}
public partial class LdapException : System.DirectoryServices.Protocols.DirectoryException, System.Runtime.Serialization.ISerializable
{
public LdapException() { }
public LdapException(int errorCode) { }
public LdapException(int errorCode, string message) { }
public LdapException(int errorCode, string message, System.Exception inner) { }
public LdapException(int errorCode, string message, string serverErrorMessage) { }
protected LdapException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public LdapException(string message) { }
public LdapException(string message, System.Exception inner) { }
public int ErrorCode { get { throw null; } }
public System.DirectoryServices.Protocols.PartialResultsCollection PartialResults { get { throw null; } }
public string ServerErrorMessage { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
}
public partial class LdapSessionOptions
{
internal LdapSessionOptions() { }
public bool AutoReconnect { get { throw null; } set { } }
public string DomainName { get { throw null; } set { } }
public string HostName { get { throw null; } set { } }
public bool HostReachable { get { throw null; } }
public System.DirectoryServices.Protocols.LocatorFlags LocatorFlag { get { throw null; } set { } }
public System.TimeSpan PingKeepAliveTimeout { get { throw null; } set { } }
public int PingLimit { get { throw null; } set { } }
public System.TimeSpan PingWaitTimeout { get { throw null; } set { } }
public int ProtocolVersion { get { throw null; } set { } }
public System.DirectoryServices.Protocols.QueryClientCertificateCallback QueryClientCertificate { get { throw null; } set { } }
public System.DirectoryServices.Protocols.ReferralCallback ReferralCallback { get { throw null; } set { } }
public System.DirectoryServices.Protocols.ReferralChasingOptions ReferralChasing { get { throw null; } set { } }
public int ReferralHopLimit { get { throw null; } set { } }
public bool RootDseCache { get { throw null; } set { } }
public string SaslMethod { get { throw null; } set { } }
public bool Sealing { get { throw null; } set { } }
public bool SecureSocketLayer { get { throw null; } set { } }
public object SecurityContext { get { throw null; } }
public System.TimeSpan SendTimeout { get { throw null; } set { } }
public bool Signing { get { throw null; } set { } }
public System.DirectoryServices.Protocols.SecurityPackageContextConnectionInformation SslInformation { get { throw null; } }
public int SspiFlag { get { throw null; } set { } }
public bool TcpKeepAlive { get { throw null; } set { } }
public System.DirectoryServices.Protocols.VerifyServerCertificateCallback VerifyServerCertificate { get { throw null; } set { } }
public void FastConcurrentBind() { }
public void StartTransportLayerSecurity(System.DirectoryServices.Protocols.DirectoryControlCollection controls) { }
public void StopTransportLayerSecurity() { }
}
[System.FlagsAttribute]
public enum LocatorFlags : long
{
None = (long)0,
ForceRediscovery = (long)1,
DirectoryServicesRequired = (long)16,
DirectoryServicesPreferred = (long)32,
GCRequired = (long)64,
PdcRequired = (long)128,
IPRequired = (long)512,
KdcRequired = (long)1024,
TimeServerRequired = (long)2048,
WriteableRequired = (long)4096,
GoodTimeServerPreferred = (long)8192,
AvoidSelf = (long)16384,
OnlyLdapNeeded = (long)32768,
IsFlatName = (long)65536,
IsDnsName = (long)131072,
ReturnDnsName = (long)1073741824,
ReturnFlatName = (long)2147483648,
}
public partial class ModifyDNRequest : System.DirectoryServices.Protocols.DirectoryRequest
{
public ModifyDNRequest() { }
public ModifyDNRequest(string distinguishedName, string newParentDistinguishedName, string newName) { }
public bool DeleteOldRdn { get { throw null; } set { } }
public string DistinguishedName { get { throw null; } set { } }
public string NewName { get { throw null; } set { } }
public string NewParentDistinguishedName { get { throw null; } set { } }
}
public partial class ModifyDNResponse : System.DirectoryServices.Protocols.DirectoryResponse
{
internal ModifyDNResponse() { }
}
public partial class ModifyRequest : System.DirectoryServices.Protocols.DirectoryRequest
{
public ModifyRequest() { }
public ModifyRequest(string distinguishedName, params System.DirectoryServices.Protocols.DirectoryAttributeModification[] modifications) { }
public ModifyRequest(string distinguishedName, System.DirectoryServices.Protocols.DirectoryAttributeOperation operation, string attributeName, params object[] values) { }
public string DistinguishedName { get { throw null; } set { } }
public System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection Modifications { get { throw null; } }
}
public partial class ModifyResponse : System.DirectoryServices.Protocols.DirectoryResponse
{
internal ModifyResponse() { }
}
public delegate bool NotifyOfNewConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection referralFromConnection, string newDistinguishedName, System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.DirectoryServices.Protocols.LdapConnection newConnection, System.Net.NetworkCredential credential, long currentUserToken, int errorCodeFromBind);
public partial class PageResultRequestControl : System.DirectoryServices.Protocols.DirectoryControl
{
public PageResultRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public PageResultRequestControl(byte[] cookie) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public PageResultRequestControl(int pageSize) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public byte[] Cookie { get { throw null; } set { } }
public int PageSize { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public partial class PageResultResponseControl : System.DirectoryServices.Protocols.DirectoryControl
{
internal PageResultResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public byte[] Cookie { get { throw null; } }
public int TotalCount { get { throw null; } }
}
public enum PartialResultProcessing
{
NoPartialResultSupport = 0,
ReturnPartialResults = 1,
ReturnPartialResultsAndNotifyCallback = 2,
}
public partial class PartialResultsCollection : System.Collections.ReadOnlyCollectionBase
{
internal PartialResultsCollection() { }
public object this[int index] { get { throw null; } }
public bool Contains(object value) { throw null; }
public void CopyTo(object[] values, int index) { }
public int IndexOf(object value) { throw null; }
}
public partial class PermissiveModifyControl : System.DirectoryServices.Protocols.DirectoryControl
{
public PermissiveModifyControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
}
public delegate System.Security.Cryptography.X509Certificates.X509Certificate QueryClientCertificateCallback(System.DirectoryServices.Protocols.LdapConnection connection, byte[][] trustedCAs);
public delegate System.DirectoryServices.Protocols.LdapConnection QueryForConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection referralFromConnection, string newDistinguishedName, System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, long currentUserToken);
public partial class QuotaControl : System.DirectoryServices.Protocols.DirectoryControl
{
public QuotaControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public QuotaControl(System.Security.Principal.SecurityIdentifier querySid) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public System.Security.Principal.SecurityIdentifier QuerySid { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public sealed partial class ReferralCallback
{
public ReferralCallback() { }
public System.DirectoryServices.Protocols.DereferenceConnectionCallback DereferenceConnection { get { throw null; } set { } }
public System.DirectoryServices.Protocols.NotifyOfNewConnectionCallback NotifyNewConnection { get { throw null; } set { } }
public System.DirectoryServices.Protocols.QueryForConnectionCallback QueryForConnection { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum ReferralChasingOptions
{
None = 0,
Subordinate = 32,
External = 64,
All = 96,
}
public enum ResultCode
{
Success = 0,
OperationsError = 1,
ProtocolError = 2,
TimeLimitExceeded = 3,
SizeLimitExceeded = 4,
CompareFalse = 5,
CompareTrue = 6,
AuthMethodNotSupported = 7,
StrongAuthRequired = 8,
ReferralV2 = 9,
Referral = 10,
AdminLimitExceeded = 11,
UnavailableCriticalExtension = 12,
ConfidentialityRequired = 13,
SaslBindInProgress = 14,
NoSuchAttribute = 16,
UndefinedAttributeType = 17,
InappropriateMatching = 18,
ConstraintViolation = 19,
AttributeOrValueExists = 20,
InvalidAttributeSyntax = 21,
NoSuchObject = 32,
AliasProblem = 33,
InvalidDNSyntax = 34,
AliasDereferencingProblem = 36,
InappropriateAuthentication = 48,
InsufficientAccessRights = 50,
Busy = 51,
Unavailable = 52,
UnwillingToPerform = 53,
LoopDetect = 54,
SortControlMissing = 60,
OffsetRangeError = 61,
NamingViolation = 64,
ObjectClassViolation = 65,
NotAllowedOnNonLeaf = 66,
NotAllowedOnRdn = 67,
EntryAlreadyExists = 68,
ObjectClassModificationsProhibited = 69,
ResultsTooLarge = 70,
AffectsMultipleDsas = 71,
VirtualListViewError = 76,
Other = 80,
}
public enum SearchOption
{
DomainScope = 1,
PhantomRoot = 2,
}
public partial class SearchOptionsControl : System.DirectoryServices.Protocols.DirectoryControl
{
public SearchOptionsControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption flags) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public System.DirectoryServices.Protocols.SearchOption SearchOption { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public partial class SearchRequest : System.DirectoryServices.Protocols.DirectoryRequest
{
public SearchRequest() { }
public SearchRequest(string distinguishedName, string ldapFilter, System.DirectoryServices.Protocols.SearchScope searchScope, params string[] attributeList) { }
public System.DirectoryServices.Protocols.DereferenceAlias Aliases { get { throw null; } set { } }
public System.Collections.Specialized.StringCollection Attributes { get { throw null; } }
public string DistinguishedName { get { throw null; } set { } }
public object Filter { get { throw null; } set { } }
public System.DirectoryServices.Protocols.SearchScope Scope { get { throw null; } set { } }
public int SizeLimit { get { throw null; } set { } }
public System.TimeSpan TimeLimit { get { throw null; } set { } }
public bool TypesOnly { get { throw null; } set { } }
}
public partial class SearchResponse : System.DirectoryServices.Protocols.DirectoryResponse
{
internal SearchResponse() { }
public override System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } }
public System.DirectoryServices.Protocols.SearchResultEntryCollection Entries { get { throw null; } }
public override string ErrorMessage { get { throw null; } }
public override string MatchedDN { get { throw null; } }
public System.DirectoryServices.Protocols.SearchResultReferenceCollection References { get { throw null; } }
public override System.Uri[] Referral { get { throw null; } }
public override System.DirectoryServices.Protocols.ResultCode ResultCode { get { throw null; } }
}
public partial class SearchResultAttributeCollection : System.Collections.DictionaryBase
{
internal SearchResultAttributeCollection() { }
public System.Collections.ICollection AttributeNames { get { throw null; } }
public System.DirectoryServices.Protocols.DirectoryAttribute this[string attributeName] { get { throw null; } }
public System.Collections.ICollection Values { get { throw null; } }
public bool Contains(string attributeName) { throw null; }
public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttribute[] array, int index) { }
}
public partial class SearchResultEntry
{
internal SearchResultEntry() { }
public System.DirectoryServices.Protocols.SearchResultAttributeCollection Attributes { get { throw null; } }
public System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } }
public string DistinguishedName { get { throw null; } }
}
public partial class SearchResultEntryCollection : System.Collections.ReadOnlyCollectionBase
{
internal SearchResultEntryCollection() { }
public System.DirectoryServices.Protocols.SearchResultEntry this[int index] { get { throw null; } }
public bool Contains(System.DirectoryServices.Protocols.SearchResultEntry value) { throw null; }
public void CopyTo(System.DirectoryServices.Protocols.SearchResultEntry[] values, int index) { }
public int IndexOf(System.DirectoryServices.Protocols.SearchResultEntry value) { throw null; }
}
public partial class SearchResultReference
{
internal SearchResultReference() { }
public System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } }
public System.Uri[] Reference { get { throw null; } }
}
public partial class SearchResultReferenceCollection : System.Collections.ReadOnlyCollectionBase
{
internal SearchResultReferenceCollection() { }
public System.DirectoryServices.Protocols.SearchResultReference this[int index] { get { throw null; } }
public bool Contains(System.DirectoryServices.Protocols.SearchResultReference value) { throw null; }
public void CopyTo(System.DirectoryServices.Protocols.SearchResultReference[] values, int index) { }
public int IndexOf(System.DirectoryServices.Protocols.SearchResultReference value) { throw null; }
}
public enum SearchScope
{
Base = 0,
OneLevel = 1,
Subtree = 2,
}
public partial class SecurityDescriptorFlagControl : System.DirectoryServices.Protocols.DirectoryControl
{
public SecurityDescriptorFlagControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public SecurityDescriptorFlagControl(System.DirectoryServices.Protocols.SecurityMasks masks) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public System.DirectoryServices.Protocols.SecurityMasks SecurityMasks { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
[System.FlagsAttribute]
public enum SecurityMasks
{
None = 0,
Owner = 1,
Group = 2,
Dacl = 4,
Sacl = 8,
}
public partial class SecurityPackageContextConnectionInformation
{
internal SecurityPackageContextConnectionInformation() { }
public System.Security.Authentication.CipherAlgorithmType AlgorithmIdentifier { get { throw null; } }
public int CipherStrength { get { throw null; } }
public int ExchangeStrength { get { throw null; } }
public System.Security.Authentication.HashAlgorithmType Hash { get { throw null; } }
public int HashStrength { get { throw null; } }
public int KeyExchangeAlgorithm { get { throw null; } }
public System.DirectoryServices.Protocols.SecurityProtocol Protocol { get { throw null; } }
}
public enum SecurityProtocol
{
Pct1Server = 1,
Pct1Client = 2,
Ssl2Server = 4,
Ssl2Client = 8,
Ssl3Server = 16,
Ssl3Client = 32,
Tls1Server = 64,
Tls1Client = 128,
}
public partial class ShowDeletedControl : System.DirectoryServices.Protocols.DirectoryControl
{
public ShowDeletedControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
}
public partial class SortKey
{
public SortKey() { }
public SortKey(string attributeName, string matchingRule, bool reverseOrder) { }
public string AttributeName { get { throw null; } set { } }
public string MatchingRule { get { throw null; } set { } }
public bool ReverseOrder { get { throw null; } set { } }
}
public partial class SortRequestControl : System.DirectoryServices.Protocols.DirectoryControl
{
public SortRequestControl(params System.DirectoryServices.Protocols.SortKey[] sortKeys) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public SortRequestControl(string attributeName, bool reverseOrder) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public SortRequestControl(string attributeName, string matchingRule, bool reverseOrder) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public System.DirectoryServices.Protocols.SortKey[] SortKeys { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public partial class SortResponseControl : System.DirectoryServices.Protocols.DirectoryControl
{
internal SortResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public string AttributeName { get { throw null; } }
public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } }
}
public partial class TlsOperationException : System.DirectoryServices.Protocols.DirectoryOperationException
{
public TlsOperationException() { }
public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response) { }
public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message) { }
public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message, System.Exception inner) { }
protected TlsOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TlsOperationException(string message) { }
public TlsOperationException(string message, System.Exception inner) { }
}
public partial class TreeDeleteControl : System.DirectoryServices.Protocols.DirectoryControl
{
public TreeDeleteControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
}
public partial class VerifyNameControl : System.DirectoryServices.Protocols.DirectoryControl
{
public VerifyNameControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public VerifyNameControl(string serverName) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public VerifyNameControl(string serverName, int flag) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public int Flag { get { throw null; } set { } }
public string ServerName { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public delegate bool VerifyServerCertificateCallback(System.DirectoryServices.Protocols.LdapConnection connection, System.Security.Cryptography.X509Certificates.X509Certificate certificate);
public partial class VlvRequestControl : System.DirectoryServices.Protocols.DirectoryControl
{
public VlvRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public VlvRequestControl(int beforeCount, int afterCount, byte[] target) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public VlvRequestControl(int beforeCount, int afterCount, int offset) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public VlvRequestControl(int beforeCount, int afterCount, string target) : base (default(string), default(byte[]), default(bool), default(bool)) { }
public int AfterCount { get { throw null; } set { } }
public int BeforeCount { get { throw null; } set { } }
public byte[] ContextId { get { throw null; } set { } }
public int EstimateCount { get { throw null; } set { } }
public int Offset { get { throw null; } set { } }
public byte[] Target { get { throw null; } set { } }
public override byte[] GetValue() { throw null; }
}
public partial class VlvResponseControl : System.DirectoryServices.Protocols.DirectoryControl
{
internal VlvResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { }
public int ContentCount { get { throw null; } }
public byte[] ContextId { get { throw null; } }
public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } }
public int TargetPosition { get { throw null; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using System.Drawing;
namespace Aga.Controls.Tree
{
public class Node
{
#region NodeCollection
private class NodeCollection : Collection<Node>
{
private Node _owner;
public NodeCollection(Node owner)
{
_owner = owner;
}
protected override void ClearItems()
{
while (this.Count != 0)
this.RemoveAt(this.Count - 1);
}
protected override void InsertItem(int index, Node item)
{
if (item == null)
throw new ArgumentNullException("item");
if (item.Parent != _owner)
{
if (item.Parent != null)
item.Parent.Nodes.Remove(item);
item._parent = _owner;
item._index = index;
for (int i = index; i < Count; i++)
this[i]._index++;
base.InsertItem(index, item);
TreeModel model = _owner.FindModel();
if (model != null)
model.OnNodeInserted(_owner, index, item);
}
}
protected override void RemoveItem(int index)
{
Node item = this[index];
item._parent = null;
item._index = -1;
for (int i = index + 1; i < Count; i++)
this[i]._index--;
base.RemoveItem(index);
TreeModel model = _owner.FindModel();
if (model != null)
model.OnNodeRemoved(_owner, index, item);
}
protected override void SetItem(int index, Node item)
{
if (item == null)
throw new ArgumentNullException("item");
RemoveAt(index);
InsertItem(index, item);
}
}
#endregion
#region Properties
private TreeModel _model;
internal TreeModel Model
{
get { return _model; }
set { _model = value; }
}
private NodeCollection _nodes;
public Collection<Node> Nodes
{
get { return _nodes; }
}
private Node _parent;
public Node Parent
{
get { return _parent; }
set
{
if (value != _parent)
{
if (_parent != null)
_parent.Nodes.Remove(this);
if (value != null)
value.Nodes.Add(this);
}
}
}
private int _index = -1;
public int Index
{
get
{
return _index;
}
}
public Node PreviousNode
{
get
{
int index = Index;
if (index > 0)
return _parent.Nodes[index - 1];
else
return null;
}
}
public Node NextNode
{
get
{
int index = Index;
if (index >= 0 && index < _parent.Nodes.Count - 1)
return _parent.Nodes[index + 1];
else
return null;
}
}
private string _text;
public virtual string Text
{
get { return _text; }
set
{
if (_text != value)
{
_text = value;
NotifyModel();
}
}
}
private bool _hidden;
public bool IsHidden
{
get { return _hidden; }
set
{
if (_hidden != value)
{
_hidden = value;
NotifyModel();
}
}
}
private CheckState _checkState;
public virtual CheckState CheckState
{
get { return _checkState; }
set
{
if (_checkState != value)
{
_checkState = value;
NotifyModel();
}
}
}
private Image _image;
public Image Image
{
get { return _image; }
set
{
if (_image != value)
{
_image = value;
NotifyModel();
}
}
}
private object _tag;
public object Tag
{
get { return _tag; }
set { _tag = value; }
}
public bool IsChecked
{
get
{
return CheckState != CheckState.Unchecked;
}
set
{
if (value)
CheckState = CheckState.Checked;
else
CheckState = CheckState.Unchecked;
}
}
public virtual bool IsLeaf
{
get
{
return false;
}
}
#endregion
public Node()
: this(string.Empty)
{
}
public Node(string text)
{
_text = text;
_nodes = new NodeCollection(this);
}
public override string ToString()
{
return Text;
}
private TreeModel FindModel()
{
Node node = this;
while (node != null)
{
if (node.Model != null)
return node.Model;
node = node.Parent;
}
return null;
}
protected void NotifyModel()
{
TreeModel model = FindModel();
if (model != null && Parent != null) model.OnNodesChanged(Parent, Index, this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System;
using System.Xml;
using System.Diagnostics;
using System.Text;
/// <summary>
/// This enum specifies what format should be used when converting string to XsdDateTime
/// </summary>
[Flags]
internal enum XsdDateTimeFlags
{
DateTime = 0x01,
Time = 0x02,
Date = 0x04,
GYearMonth = 0x08,
GYear = 0x10,
GMonthDay = 0x20,
GDay = 0x40,
GMonth = 0x80,
#if !SILVERLIGHT // XDR is not supported in Silverlight
XdrDateTimeNoTz = 0x100,
XdrDateTime = 0x200,
XdrTimeNoTz = 0x400, //XDRTime with tz is the same as xsd:time
#endif
AllXsd = 0xFF //All still does not include the XDR formats
}
/// <summary>
/// This structure extends System.DateTime to support timeInTicks zone and Gregorian types scomponents of an Xsd Duration. It is used internally to support Xsd durations without loss
/// of fidelity. XsdDuration structures are immutable once they've been created.
/// </summary>
internal struct XsdDateTime
{
// DateTime is being used as an internal representation only
// Casting XsdDateTime to DateTime might return a different value
private DateTime _dt;
// Additional information that DateTime is not preserving
// Information is stored in the following format:
// Bits Info
// 31-24 DateTimeTypeCode
// 23-16 XsdDateTimeKind
// 15-8 Zone Hours
// 7-0 Zone Minutes
private uint _extra;
// Subset of XML Schema types XsdDateTime represents
private enum DateTimeTypeCode
{
DateTime,
Time,
Date,
GYearMonth,
GYear,
GMonthDay,
GDay,
GMonth,
#if !SILVERLIGHT // XDR is not supported in Silverlight
XdrDateTime,
#endif
}
// Internal representation of DateTimeKind
private enum XsdDateTimeKind
{
Unspecified,
Zulu,
LocalWestOfZulu, // GMT-1..14, N..Y
LocalEastOfZulu // GMT+1..14, A..M
}
// Masks and shifts used for packing and unpacking extra
private const uint TypeMask = 0xFF000000;
private const uint KindMask = 0x00FF0000;
private const uint ZoneHourMask = 0x0000FF00;
private const uint ZoneMinuteMask = 0x000000FF;
private const int TypeShift = 24;
private const int KindShift = 16;
private const int ZoneHourShift = 8;
// Maximum number of fraction digits;
private const short maxFractionDigits = 7;
private static readonly int s_lzyyyy = "yyyy".Length;
private static readonly int s_lzyyyy_ = "yyyy-".Length;
private static readonly int s_lzyyyy_MM = "yyyy-MM".Length;
private static readonly int s_lzyyyy_MM_ = "yyyy-MM-".Length;
private static readonly int s_lzyyyy_MM_dd = "yyyy-MM-dd".Length;
private static readonly int s_lzyyyy_MM_ddT = "yyyy-MM-ddT".Length;
private static readonly int s_lzHH = "HH".Length;
private static readonly int s_lzHH_ = "HH:".Length;
private static readonly int s_lzHH_mm = "HH:mm".Length;
private static readonly int s_lzHH_mm_ = "HH:mm:".Length;
private static readonly int s_lzHH_mm_ss = "HH:mm:ss".Length;
private static readonly int s_Lz_ = "-".Length;
private static readonly int s_lz_zz = "-zz".Length;
private static readonly int s_lz_zz_ = "-zz:".Length;
private static readonly int s_lz_zz_zz = "-zz:zz".Length;
private static readonly int s_Lz__ = "--".Length;
private static readonly int s_lz__mm = "--MM".Length;
private static readonly int s_lz__mm_ = "--MM-".Length;
private static readonly int s_lz__mm__ = "--MM--".Length;
private static readonly int s_lz__mm_dd = "--MM-dd".Length;
private static readonly int s_Lz___ = "---".Length;
private static readonly int s_lz___dd = "---dd".Length;
#if !SILVERLIGHT
/// <summary>
/// Constructs an XsdDateTime from a string trying all possible formats.
/// </summary>
public XsdDateTime(string text) : this(text, XsdDateTimeFlags.AllXsd)
{
}
#endif
/// <summary>
/// Constructs an XsdDateTime from a string using specific format.
/// </summary>
public XsdDateTime(string text, XsdDateTimeFlags kinds) : this()
{
Parser parser = new Parser();
if (!parser.Parse(text, kinds))
{
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, text, kinds));
}
InitiateXsdDateTime(parser);
}
#if !SILVERLIGHT
private XsdDateTime(Parser parser) : this()
{
InitiateXsdDateTime(parser);
}
#endif
private void InitiateXsdDateTime(Parser parser)
{
_dt = new DateTime(parser.year, parser.month, parser.day, parser.hour, parser.minute, parser.second);
if (parser.fraction != 0)
{
_dt = _dt.AddTicks(parser.fraction);
}
_extra = (uint)(((int)parser.typeCode << TypeShift) | ((int)parser.kind << KindShift) | (parser.zoneHour << ZoneHourShift) | parser.zoneMinute);
}
#if !SILVERLIGHT
internal static bool TryParse(string text, XsdDateTimeFlags kinds, out XsdDateTime result)
{
Parser parser = new Parser();
if (!parser.Parse(text, kinds))
{
result = new XsdDateTime();
return false;
}
result = new XsdDateTime(parser);
return true;
}
#endif
/// <summary>
/// Constructs an XsdDateTime from a DateTime.
/// </summary>
public XsdDateTime(DateTime dateTime, XsdDateTimeFlags kinds)
{
Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set.");
_dt = dateTime;
DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1);
int zoneHour = 0;
int zoneMinute = 0;
XsdDateTimeKind kind;
switch (dateTime.Kind)
{
case DateTimeKind.Unspecified: kind = XsdDateTimeKind.Unspecified; break;
case DateTimeKind.Utc: kind = XsdDateTimeKind.Zulu; break;
default:
{
Debug.Assert(dateTime.Kind == DateTimeKind.Local, "Unknown DateTimeKind: " + dateTime.Kind);
TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(dateTime);
if (utcOffset.Ticks < 0)
{
kind = XsdDateTimeKind.LocalWestOfZulu;
zoneHour = -utcOffset.Hours;
zoneMinute = -utcOffset.Minutes;
}
else
{
kind = XsdDateTimeKind.LocalEastOfZulu;
zoneHour = utcOffset.Hours;
zoneMinute = utcOffset.Minutes;
}
break;
}
}
_extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneHour << ZoneHourShift) | zoneMinute);
}
// Constructs an XsdDateTime from a DateTimeOffset
public XsdDateTime(DateTimeOffset dateTimeOffset) : this(dateTimeOffset, XsdDateTimeFlags.DateTime)
{
}
public XsdDateTime(DateTimeOffset dateTimeOffset, XsdDateTimeFlags kinds)
{
Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set.");
_dt = dateTimeOffset.DateTime;
TimeSpan zoneOffset = dateTimeOffset.Offset;
DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1);
XsdDateTimeKind kind;
if (zoneOffset.TotalMinutes < 0)
{
zoneOffset = zoneOffset.Negate();
kind = XsdDateTimeKind.LocalWestOfZulu;
}
else if (zoneOffset.TotalMinutes > 0)
{
kind = XsdDateTimeKind.LocalEastOfZulu;
}
else
{
kind = XsdDateTimeKind.Zulu;
}
_extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneOffset.Hours << ZoneHourShift) | zoneOffset.Minutes);
}
/// <summary>
/// Returns auxiliary enumeration of XSD date type
/// </summary>
private DateTimeTypeCode InternalTypeCode
{
get { return (DateTimeTypeCode)((_extra & TypeMask) >> TypeShift); }
}
/// <summary>
/// Returns geographical "position" of the value
/// </summary>
private XsdDateTimeKind InternalKind
{
get { return (XsdDateTimeKind)((_extra & KindMask) >> KindShift); }
}
#if !SILVERLIGHT
/// <summary>
/// Returns XmlTypeCode of the value being stored
/// </summary>
public XmlTypeCode TypeCode
{
get { return s_typeCodes[(int)InternalTypeCode]; }
}
/// <summary>
/// Returns whether object represent local, UTC or unspecified time
/// </summary>
public DateTimeKind Kind
{
get
{
switch (InternalKind)
{
case XsdDateTimeKind.Unspecified:
return DateTimeKind.Unspecified;
case XsdDateTimeKind.Zulu:
return DateTimeKind.Utc;
default:
// XsdDateTimeKind.LocalEastOfZulu:
// XsdDateTimeKind.LocalWestOfZulu:
return DateTimeKind.Local;
}
}
}
#endif
/// <summary>
/// Returns the year part of XsdDateTime
/// The returned value is integer between 1 and 9999
/// </summary>
public int Year
{
get { return _dt.Year; }
}
/// <summary>
/// Returns the month part of XsdDateTime
/// The returned value is integer between 1 and 12
/// </summary>
public int Month
{
get { return _dt.Month; }
}
/// <summary>
/// Returns the day of the month part of XsdDateTime
/// The returned value is integer between 1 and 31
/// </summary>
public int Day
{
get { return _dt.Day; }
}
/// <summary>
/// Returns the hour part of XsdDateTime
/// The returned value is integer between 0 and 23
/// </summary>
public int Hour
{
get { return _dt.Hour; }
}
/// <summary>
/// Returns the minute part of XsdDateTime
/// The returned value is integer between 0 and 60
/// </summary>
public int Minute
{
get { return _dt.Minute; }
}
/// <summary>
/// Returns the second part of XsdDateTime
/// The returned value is integer between 0 and 60
/// </summary>
public int Second
{
get { return _dt.Second; }
}
/// <summary>
/// Returns number of ticks in the fraction of the second
/// The returned value is integer between 0 and 9999999
/// </summary>
public int Fraction
{
get { return (int)(_dt.Ticks - new DateTime(_dt.Year, _dt.Month, _dt.Day, _dt.Hour, _dt.Minute, _dt.Second).Ticks); }
}
/// <summary>
/// Returns the hour part of the time zone
/// The returned value is integer between -13 and 13
/// </summary>
public int ZoneHour
{
get
{
uint result = (_extra & ZoneHourMask) >> ZoneHourShift;
return (int)result;
}
}
/// <summary>
/// Returns the minute part of the time zone
/// The returned value is integer between 0 and 60
/// </summary>
public int ZoneMinute
{
get
{
uint result = (_extra & ZoneMinuteMask);
return (int)result;
}
}
#if !SILVERLIGHT
public DateTime ToZulu()
{
switch (InternalKind)
{
case XsdDateTimeKind.Zulu:
// set it to UTC
return new DateTime(_dt.Ticks, DateTimeKind.Utc);
case XsdDateTimeKind.LocalEastOfZulu:
// Adjust to UTC and then convert to local in the current time zone
return new DateTime(_dt.Subtract(new TimeSpan(ZoneHour, ZoneMinute, 0)).Ticks, DateTimeKind.Utc);
case XsdDateTimeKind.LocalWestOfZulu:
// Adjust to UTC and then convert to local in the current time zone
return new DateTime(_dt.Add(new TimeSpan(ZoneHour, ZoneMinute, 0)).Ticks, DateTimeKind.Utc);
default:
return _dt;
}
}
#endif
/// <summary>
/// Cast to DateTime
/// The following table describes the behaviors of getting the default value
/// when a certain year/month/day values are missing.
///
/// An "X" means that the value exists. And "--" means that value is missing.
///
/// Year Month Day => ResultYear ResultMonth ResultDay Note
///
/// X X X Parsed year Parsed month Parsed day
/// X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month.
/// X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year.
/// X -- -- Parsed year First month First day If we have only the year, assume the first day of that year.
///
/// -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year.
/// -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day.
/// -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month.
/// -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date.
/// </summary>
public static implicit operator DateTime(XsdDateTime xdt)
{
DateTime result;
switch (xdt.InternalTypeCode)
{
case DateTimeTypeCode.GMonth:
case DateTimeTypeCode.GDay:
result = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day);
break;
case DateTimeTypeCode.Time:
//back to DateTime.Now
DateTime currentDateTime = DateTime.Now;
TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day);
result = xdt._dt.Add(addDiff);
break;
default:
result = xdt._dt;
break;
}
long ticks;
switch (xdt.InternalKind)
{
case XsdDateTimeKind.Zulu:
// set it to UTC
result = new DateTime(result.Ticks, DateTimeKind.Utc);
break;
case XsdDateTimeKind.LocalEastOfZulu:
// Adjust to UTC and then convert to local in the current time zone
ticks = result.Ticks - new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks;
if (ticks < DateTime.MinValue.Ticks)
{
// Underflow. Return the DateTime as local time directly
ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks;
if (ticks < DateTime.MinValue.Ticks)
ticks = DateTime.MinValue.Ticks;
return new DateTime(ticks, DateTimeKind.Local);
}
result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
break;
case XsdDateTimeKind.LocalWestOfZulu:
// Adjust to UTC and then convert to local in the current time zone
ticks = result.Ticks + new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks;
if (ticks > DateTime.MaxValue.Ticks)
{
// Overflow. Return the DateTime as local time directly
ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks;
if (ticks > DateTime.MaxValue.Ticks)
ticks = DateTime.MaxValue.Ticks;
return new DateTime(ticks, DateTimeKind.Local);
}
result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
break;
default:
break;
}
return result;
}
public static implicit operator DateTimeOffset(XsdDateTime xdt)
{
DateTime dt;
switch (xdt.InternalTypeCode)
{
case DateTimeTypeCode.GMonth:
case DateTimeTypeCode.GDay:
dt = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day);
break;
case DateTimeTypeCode.Time:
//back to DateTime.Now
DateTime currentDateTime = DateTime.Now;
TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day);
dt = xdt._dt.Add(addDiff);
break;
default:
dt = xdt._dt;
break;
}
DateTimeOffset result;
switch (xdt.InternalKind)
{
case XsdDateTimeKind.LocalEastOfZulu:
result = new DateTimeOffset(dt, new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0));
break;
case XsdDateTimeKind.LocalWestOfZulu:
result = new DateTimeOffset(dt, new TimeSpan(-xdt.ZoneHour, -xdt.ZoneMinute, 0));
break;
case XsdDateTimeKind.Zulu:
result = new DateTimeOffset(dt, new TimeSpan(0));
break;
case XsdDateTimeKind.Unspecified:
default:
result = new DateTimeOffset(dt, TimeZoneInfo.Local.GetUtcOffset(dt));
break;
}
return result;
}
#if !SILVERLIGHT
/// <summary>
/// Compares two DateTime values, returning an integer that indicates
/// their relationship.
/// </summary>
public static int Compare(XsdDateTime left, XsdDateTime right)
{
if (left._extra == right._extra)
{
return DateTime.Compare(left._dt, right._dt);
}
else
{
// Xsd types should be the same for it to be comparable
if (left.InternalTypeCode != right.InternalTypeCode)
{
throw new ArgumentException(SR.Format(SR.Sch_XsdDateTimeCompare, left.TypeCode, right.TypeCode));
}
// Convert both to UTC
return DateTime.Compare(left.GetZuluDateTime(), right.GetZuluDateTime());
}
}
// Compares this DateTime to a given object. This method provides an
// implementation of the IComparable interface. The object
// argument must be another DateTime, or otherwise an exception
// occurs. Null is considered less than any instance.
//
// Returns a value less than zero if this object
/// <include file='doc\DateTime.uex' path='docs/doc[@for="DateTime.CompareTo"]/*' />
public int CompareTo(Object value)
{
if (value == null) return 1;
return Compare(this, (XsdDateTime)value);
}
#endif
/// <summary>
/// Serialization to a string
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder(64);
char[] text;
switch (InternalTypeCode)
{
case DateTimeTypeCode.DateTime:
PrintDate(sb);
sb.Append('T');
PrintTime(sb);
break;
case DateTimeTypeCode.Time:
PrintTime(sb);
break;
case DateTimeTypeCode.Date:
PrintDate(sb);
break;
case DateTimeTypeCode.GYearMonth:
text = new char[s_lzyyyy_MM];
IntToCharArray(text, 0, Year, 4);
text[s_lzyyyy] = '-';
ShortToCharArray(text, s_lzyyyy_, Month);
sb.Append(text);
break;
case DateTimeTypeCode.GYear:
text = new char[s_lzyyyy];
IntToCharArray(text, 0, Year, 4);
sb.Append(text);
break;
case DateTimeTypeCode.GMonthDay:
text = new char[s_lz__mm_dd];
text[0] = '-';
text[s_Lz_] = '-';
ShortToCharArray(text, s_Lz__, Month);
text[s_lz__mm] = '-';
ShortToCharArray(text, s_lz__mm_, Day);
sb.Append(text);
break;
case DateTimeTypeCode.GDay:
text = new char[s_lz___dd];
text[0] = '-';
text[s_Lz_] = '-';
text[s_Lz__] = '-';
ShortToCharArray(text, s_Lz___, Day);
sb.Append(text);
break;
case DateTimeTypeCode.GMonth:
text = new char[s_lz__mm__];
text[0] = '-';
text[s_Lz_] = '-';
ShortToCharArray(text, s_Lz__, Month);
text[s_lz__mm] = '-';
text[s_lz__mm_] = '-';
sb.Append(text);
break;
}
PrintZone(sb);
return sb.ToString();
}
// Serialize year, month and day
private void PrintDate(StringBuilder sb)
{
char[] text = new char[s_lzyyyy_MM_dd];
IntToCharArray(text, 0, Year, 4);
text[s_lzyyyy] = '-';
ShortToCharArray(text, s_lzyyyy_, Month);
text[s_lzyyyy_MM] = '-';
ShortToCharArray(text, s_lzyyyy_MM_, Day);
sb.Append(text);
}
// Serialize hour, minute, second and fraction
private void PrintTime(StringBuilder sb)
{
char[] text = new char[s_lzHH_mm_ss];
ShortToCharArray(text, 0, Hour);
text[s_lzHH] = ':';
ShortToCharArray(text, s_lzHH_, Minute);
text[s_lzHH_mm] = ':';
ShortToCharArray(text, s_lzHH_mm_, Second);
sb.Append(text);
int fraction = Fraction;
if (fraction != 0)
{
int fractionDigits = maxFractionDigits;
while (fraction % 10 == 0)
{
fractionDigits--;
fraction /= 10;
}
text = new char[fractionDigits + 1];
text[0] = '.';
IntToCharArray(text, 1, fraction, fractionDigits);
sb.Append(text);
}
}
// Serialize time zone
private void PrintZone(StringBuilder sb)
{
char[] text;
switch (InternalKind)
{
case XsdDateTimeKind.Zulu:
sb.Append('Z');
break;
case XsdDateTimeKind.LocalWestOfZulu:
text = new char[s_lz_zz_zz];
text[0] = '-';
ShortToCharArray(text, s_Lz_, ZoneHour);
text[s_lz_zz] = ':';
ShortToCharArray(text, s_lz_zz_, ZoneMinute);
sb.Append(text);
break;
case XsdDateTimeKind.LocalEastOfZulu:
text = new char[s_lz_zz_zz];
text[0] = '+';
ShortToCharArray(text, s_Lz_, ZoneHour);
text[s_lz_zz] = ':';
ShortToCharArray(text, s_lz_zz_, ZoneMinute);
sb.Append(text);
break;
default:
// do nothing
break;
}
}
// Serialize integer into character array starting with index [start].
// Number of digits is set by [digits]
private void IntToCharArray(char[] text, int start, int value, int digits)
{
while (digits-- != 0)
{
text[start + digits] = (char)(value % 10 + '0');
value /= 10;
}
}
// Serialize two digit integer into character array starting with index [start].
private void ShortToCharArray(char[] text, int start, int value)
{
text[start] = (char)(value / 10 + '0');
text[start + 1] = (char)(value % 10 + '0');
}
#if !SILVERLIGHT
// Auxiliary for compare.
// Returns UTC DateTime
private DateTime GetZuluDateTime()
{
switch (InternalKind)
{
case XsdDateTimeKind.Zulu:
return _dt;
case XsdDateTimeKind.LocalEastOfZulu:
return _dt.Subtract(new TimeSpan(ZoneHour, ZoneMinute, 0));
case XsdDateTimeKind.LocalWestOfZulu:
return _dt.Add(new TimeSpan(ZoneHour, ZoneMinute, 0));
default:
return _dt.ToUniversalTime();
}
}
#endif
private static readonly XmlTypeCode[] s_typeCodes = {
XmlTypeCode.DateTime,
XmlTypeCode.Time,
XmlTypeCode.Date,
XmlTypeCode.GYearMonth,
XmlTypeCode.GYear,
XmlTypeCode.GMonthDay,
XmlTypeCode.GDay,
XmlTypeCode.GMonth
};
// Parsing string according to XML schema spec
private struct Parser
{
private const int leapYear = 1904;
private const int firstMonth = 1;
private const int firstDay = 1;
public DateTimeTypeCode typeCode;
public int year;
public int month;
public int day;
public int hour;
public int minute;
public int second;
public int fraction;
public XsdDateTimeKind kind;
public int zoneHour;
public int zoneMinute;
private string _text;
private int _length;
public bool Parse(string text, XsdDateTimeFlags kinds)
{
_text = text;
_length = text.Length;
// Skip leading withitespace
int start = 0;
while (start < _length && char.IsWhiteSpace(text[start]))
{
start++;
}
// Choose format starting from the most common and trying not to reparse the same thing too many times
#if !SILVERLIGHT // XDR is not supported in Silverlight
if (Test(kinds, XsdDateTimeFlags.DateTime | XsdDateTimeFlags.Date | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrDateTimeNoTz))
{
#else
if (Test(kinds, XsdDateTimeFlags.DateTime | XsdDateTimeFlags.Date)) {
#endif
if (ParseDate(start))
{
if (Test(kinds, XsdDateTimeFlags.DateTime))
{
if (ParseChar(start + s_lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + s_lzyyyy_MM_ddT))
{
typeCode = DateTimeTypeCode.DateTime;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.Date))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy_MM_dd))
{
typeCode = DateTimeTypeCode.Date;
return true;
}
}
#if !SILVERLIGHT // XDR is not supported in Silverlight
if (Test(kinds, XsdDateTimeFlags.XdrDateTime))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy_MM_dd) || (ParseChar(start + s_lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + s_lzyyyy_MM_ddT)))
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.XdrDateTimeNoTz))
{
if (ParseChar(start + s_lzyyyy_MM_dd, 'T'))
{
if (ParseTimeAndWhitespace(start + s_lzyyyy_MM_ddT))
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
else
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
#endif
}
}
if (Test(kinds, XsdDateTimeFlags.Time))
{
if (ParseTimeAndZoneAndWhitespace(start))
{ //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time
year = leapYear;
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.Time;
return true;
}
}
#if !SILVERLIGHT // XDR is not supported in Silverlight
if (Test(kinds, XsdDateTimeFlags.XdrTimeNoTz))
{
if (ParseTimeAndWhitespace(start))
{ //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time
year = leapYear;
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.Time;
return true;
}
}
#endif
if (Test(kinds, XsdDateTimeFlags.GYearMonth | XsdDateTimeFlags.GYear))
{
if (Parse4Dig(start, ref year) && 1 <= year)
{
if (Test(kinds, XsdDateTimeFlags.GYearMonth))
{
if (
ParseChar(start + s_lzyyyy, '-') &&
Parse2Dig(start + s_lzyyyy_, ref month) && 1 <= month && month <= 12 &&
ParseZoneAndWhitespace(start + s_lzyyyy_MM)
)
{
day = firstDay;
typeCode = DateTimeTypeCode.GYearMonth;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GYear))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy))
{
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.GYear;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.GMonthDay | XsdDateTimeFlags.GMonth))
{
if (
ParseChar(start, '-') &&
ParseChar(start + s_Lz_, '-') &&
Parse2Dig(start + s_Lz__, ref month) && 1 <= month && month <= 12
)
{
if (Test(kinds, XsdDateTimeFlags.GMonthDay) && ParseChar(start + s_lz__mm, '-'))
{
if (
Parse2Dig(start + s_lz__mm_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, month) &&
ParseZoneAndWhitespace(start + s_lz__mm_dd)
)
{
year = leapYear;
typeCode = DateTimeTypeCode.GMonthDay;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GMonth))
{
if (ParseZoneAndWhitespace(start + s_lz__mm) || (ParseChar(start + s_lz__mm, '-') && ParseChar(start + s_lz__mm_, '-') && ParseZoneAndWhitespace(start + s_lz__mm__)))
{
year = leapYear;
day = firstDay;
typeCode = DateTimeTypeCode.GMonth;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.GDay))
{
if (
ParseChar(start, '-') &&
ParseChar(start + s_Lz_, '-') &&
ParseChar(start + s_Lz__, '-') &&
Parse2Dig(start + s_Lz___, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, firstMonth) &&
ParseZoneAndWhitespace(start + s_lz___dd)
)
{
year = leapYear;
month = firstMonth;
typeCode = DateTimeTypeCode.GDay;
return true;
}
}
return false;
}
private bool ParseDate(int start)
{
return
Parse4Dig(start, ref year) && 1 <= year &&
ParseChar(start + s_lzyyyy, '-') &&
Parse2Dig(start + s_lzyyyy_, ref month) && 1 <= month && month <= 12 &&
ParseChar(start + s_lzyyyy_MM, '-') &&
Parse2Dig(start + s_lzyyyy_MM_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(year, month);
}
private bool ParseTimeAndZoneAndWhitespace(int start)
{
if (ParseTime(ref start))
{
if (ParseZoneAndWhitespace(start))
{
return true;
}
}
return false;
}
#if !SILVERLIGHT // XDR is not supported in Silverlight
private bool ParseTimeAndWhitespace(int start)
{
if (ParseTime(ref start))
{
while (start < _length)
{//&& char.IsWhiteSpace(text[start])) {
start++;
}
return start == _length;
}
return false;
}
#endif
private static int[] s_power10 = new int[maxFractionDigits] { -1, 10, 100, 1000, 10000, 100000, 1000000 };
private bool ParseTime(ref int start)
{
if (
Parse2Dig(start, ref hour) && hour < 24 &&
ParseChar(start + s_lzHH, ':') &&
Parse2Dig(start + s_lzHH_, ref minute) && minute < 60 &&
ParseChar(start + s_lzHH_mm, ':') &&
Parse2Dig(start + s_lzHH_mm_, ref second) && second < 60
)
{
start += s_lzHH_mm_ss;
if (ParseChar(start, '.'))
{
// Parse factional part of seconds
// We allow any number of digits, but keep only first 7
this.fraction = 0;
int fractionDigits = 0;
int round = 0;
while (++start < _length)
{
int d = _text[start] - '0';
if (9u < (uint)d)
{ // d < 0 || 9 < d
break;
}
if (fractionDigits < maxFractionDigits)
{
this.fraction = (this.fraction * 10) + d;
}
else if (fractionDigits == maxFractionDigits)
{
if (5 < d)
{
round = 1;
}
else if (d == 5)
{
round = -1;
}
}
else if (round < 0 && d != 0)
{
round = 1;
}
fractionDigits++;
}
if (fractionDigits < maxFractionDigits)
{
if (fractionDigits == 0)
{
return false; // cannot end with .
}
fraction *= s_power10[maxFractionDigits - fractionDigits];
}
else
{
if (round < 0)
{
round = fraction & 1;
}
fraction += round;
}
}
return true;
}
// cleanup - conflict with gYear
hour = 0;
return false;
}
private bool ParseZoneAndWhitespace(int start)
{
if (start < _length)
{
char ch = _text[start];
if (ch == 'Z' || ch == 'z')
{
kind = XsdDateTimeKind.Zulu;
start++;
}
else if (start + 5 < _length)
{
if (
Parse2Dig(start + s_Lz_, ref zoneHour) && zoneHour <= 99 &&
ParseChar(start + s_lz_zz, ':') &&
Parse2Dig(start + s_lz_zz_, ref zoneMinute) && zoneMinute <= 99
)
{
if (ch == '-')
{
kind = XsdDateTimeKind.LocalWestOfZulu;
start += s_lz_zz_zz;
}
else if (ch == '+')
{
kind = XsdDateTimeKind.LocalEastOfZulu;
start += s_lz_zz_zz;
}
}
}
}
while (start < _length && char.IsWhiteSpace(_text[start]))
{
start++;
}
return start == _length;
}
private bool Parse4Dig(int start, ref int num)
{
if (start + 3 < _length)
{
int d4 = _text[start] - '0';
int d3 = _text[start + 1] - '0';
int d2 = _text[start + 2] - '0';
int d1 = _text[start + 3] - '0';
if (0 <= d4 && d4 < 10 &&
0 <= d3 && d3 < 10 &&
0 <= d2 && d2 < 10 &&
0 <= d1 && d1 < 10
)
{
num = ((d4 * 10 + d3) * 10 + d2) * 10 + d1;
return true;
}
}
return false;
}
private bool Parse2Dig(int start, ref int num)
{
if (start + 1 < _length)
{
int d2 = _text[start] - '0';
int d1 = _text[start + 1] - '0';
if (0 <= d2 && d2 < 10 &&
0 <= d1 && d1 < 10
)
{
num = d2 * 10 + d1;
return true;
}
}
return false;
}
private bool ParseChar(int start, char ch)
{
return start < _length && _text[start] == ch;
}
private static bool Test(XsdDateTimeFlags left, XsdDateTimeFlags right)
{
return (left & right) != 0;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for IntegrationAccountAgreementsOperations.
/// </summary>
public static partial class IntegrationAccountAgreementsOperationsExtensions
{
/// <summary>
/// Gets a list of integration account agreements.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<IntegrationAccountAgreement> List(this IIntegrationAccountAgreementsOperations operations, string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountAgreementFilter> odataQuery = default(ODataQuery<IntegrationAccountAgreementFilter>))
{
return Task.Factory.StartNew(s => ((IIntegrationAccountAgreementsOperations)s).ListAsync(resourceGroupName, integrationAccountName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of integration account agreements.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IntegrationAccountAgreement>> ListAsync(this IIntegrationAccountAgreementsOperations operations, string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountAgreementFilter> odataQuery = default(ODataQuery<IntegrationAccountAgreementFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, integrationAccountName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an integration account agreement.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='agreementName'>
/// The integration account agreement name.
/// </param>
public static IntegrationAccountAgreement Get(this IIntegrationAccountAgreementsOperations operations, string resourceGroupName, string integrationAccountName, string agreementName)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountAgreementsOperations)s).GetAsync(resourceGroupName, integrationAccountName, agreementName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an integration account agreement.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='agreementName'>
/// The integration account agreement name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntegrationAccountAgreement> GetAsync(this IIntegrationAccountAgreementsOperations operations, string resourceGroupName, string integrationAccountName, string agreementName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, integrationAccountName, agreementName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates an integration account agreement.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='agreementName'>
/// The integration account agreement name.
/// </param>
/// <param name='agreement'>
/// The integration account agreement.
/// </param>
public static IntegrationAccountAgreement CreateOrUpdate(this IIntegrationAccountAgreementsOperations operations, string resourceGroupName, string integrationAccountName, string agreementName, IntegrationAccountAgreement agreement)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountAgreementsOperations)s).CreateOrUpdateAsync(resourceGroupName, integrationAccountName, agreementName, agreement), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an integration account agreement.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='agreementName'>
/// The integration account agreement name.
/// </param>
/// <param name='agreement'>
/// The integration account agreement.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntegrationAccountAgreement> CreateOrUpdateAsync(this IIntegrationAccountAgreementsOperations operations, string resourceGroupName, string integrationAccountName, string agreementName, IntegrationAccountAgreement agreement, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, integrationAccountName, agreementName, agreement, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an integration account agreement.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='agreementName'>
/// The integration account agreement name.
/// </param>
public static void Delete(this IIntegrationAccountAgreementsOperations operations, string resourceGroupName, string integrationAccountName, string agreementName)
{
Task.Factory.StartNew(s => ((IIntegrationAccountAgreementsOperations)s).DeleteAsync(resourceGroupName, integrationAccountName, agreementName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an integration account agreement.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='agreementName'>
/// The integration account agreement name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IIntegrationAccountAgreementsOperations operations, string resourceGroupName, string integrationAccountName, string agreementName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, integrationAccountName, agreementName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a list of integration account agreements.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<IntegrationAccountAgreement> ListNext(this IIntegrationAccountAgreementsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IIntegrationAccountAgreementsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of integration account agreements.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IntegrationAccountAgreement>> ListNextAsync(this IIntegrationAccountAgreementsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
namespace Amib.Threading.Internal
{
#region WorkItemFactory class
public class WorkItemFactory
{
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback)
{
return CreateWorkItem(workItemsGroup, wigStartInfo, callback, null);
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="workItemPriority">The priority of the work item</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
WorkItemPriority workItemPriority)
{
return CreateWorkItem(workItemsGroup, wigStartInfo, callback, null, workItemPriority);
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="workItemInfo">Work item info</param>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemInfo workItemInfo,
WorkItemCallback callback)
{
return CreateWorkItem(
workItemsGroup,
wigStartInfo,
workItemInfo,
callback,
null);
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state)
{
ValidateCallback(callback);
WorkItemInfo workItemInfo = new WorkItemInfo();
workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext;
workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext;
workItemInfo.PostExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback;
workItemInfo.CallToPostExecute = wigStartInfo.CallToPostExecute;
workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects;
workItemInfo.WorkItemPriority = wigStartInfo.WorkItemPriority;
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The work items group</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
WorkItemPriority workItemPriority)
{
ValidateCallback(callback);
WorkItemInfo workItemInfo = new WorkItemInfo();
workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext;
workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext;
workItemInfo.PostExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback;
workItemInfo.CallToPostExecute = wigStartInfo.CallToPostExecute;
workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects;
workItemInfo.WorkItemPriority = workItemPriority;
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The work items group</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="workItemInfo">Work item information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemInfo workItemInfo,
WorkItemCallback callback,
object state)
{
ValidateCallback(callback);
ValidateCallback(workItemInfo.PostExecuteWorkItemCallback);
WorkItem workItem = new WorkItem(
workItemsGroup,
new WorkItemInfo(workItemInfo),
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The work items group</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback)
{
ValidateCallback(callback);
ValidateCallback(postExecuteWorkItemCallback);
WorkItemInfo workItemInfo = new WorkItemInfo();
workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext;
workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext;
workItemInfo.PostExecuteWorkItemCallback = postExecuteWorkItemCallback;
workItemInfo.CallToPostExecute = wigStartInfo.CallToPostExecute;
workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects;
workItemInfo.WorkItemPriority = wigStartInfo.WorkItemPriority;
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The work items group</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
WorkItemPriority workItemPriority)
{
ValidateCallback(callback);
ValidateCallback(postExecuteWorkItemCallback);
WorkItemInfo workItemInfo = new WorkItemInfo();
workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext;
workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext;
workItemInfo.PostExecuteWorkItemCallback = postExecuteWorkItemCallback;
workItemInfo.CallToPostExecute = wigStartInfo.CallToPostExecute;
workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects;
workItemInfo.WorkItemPriority = workItemPriority;
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The work items group</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute)
{
ValidateCallback(callback);
ValidateCallback(postExecuteWorkItemCallback);
WorkItemInfo workItemInfo = new WorkItemInfo();
workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext;
workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext;
workItemInfo.PostExecuteWorkItemCallback = postExecuteWorkItemCallback;
workItemInfo.CallToPostExecute = callToPostExecute;
workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects;
workItemInfo.WorkItemPriority = wigStartInfo.WorkItemPriority;
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name="workItemsGroup">The work items group</param>
/// <param name="wigStartInfo">Work item group start information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute,
WorkItemPriority workItemPriority)
{
ValidateCallback(callback);
ValidateCallback(postExecuteWorkItemCallback);
WorkItemInfo workItemInfo = new WorkItemInfo();
workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext;
workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext;
workItemInfo.PostExecuteWorkItemCallback = postExecuteWorkItemCallback;
workItemInfo.CallToPostExecute = callToPostExecute;
workItemInfo.WorkItemPriority = workItemPriority;
workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects;
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
private static void ValidateCallback(Delegate callback)
{
if(callback.GetInvocationList().Length > 1)
{
throw new NotSupportedException("SmartThreadPool doesn't support delegates chains");
}
}
}
#endregion
}
| |
using Plugin.CropImage.Abstractions;
using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
namespace Plugin.CropImage {
/// <summary>
/// Implementation for Feature
/// </summary>
public class CropImageImplementation : ICropImage {
/// <summary>
/// Crops an image by the BoundingBox and returns in the size you specify.
/// The new image will be saved on the device.
/// </summary>
/// <param name="originalSourcePath">The original SourcePath to a file on Device</param>
/// <param name="boundingBox">The image box that will be used to crop</param>
/// <param name="width">Width of the cropped image</param>
/// <param name="height">Height of the cropped image</param>
/// <param name="addToFilename">What string should be after the originalSourcePath. if original is img20161203.jpg and addToFileName is -thumbnail then the outcome will be img20161203-thumbnail.jpg</param>
/// /// <param name="removeFromOriginalSourceFilename">a string that should be removed from original source ex. originalSourcepath = "Image-fullImage.jpg" removeFromOriginalSourceFilename = "-fullImage" the resulting path string will be "Image"+"addToFilename+".jpg"</param>
/// <returns>The path to the cropped image</returns>
async public Task<string> CropImage(string originalSourcePath, BoundingBox boundingBox, int width, int height, string addToFilename, string removeFromOriginalSourceFilename = null) {
var downSampledPath = await FixMaxImageSize(originalSourcePath, 4000000);
var newFile = await MakeCopyOfFile(downSampledPath, addToFilename, removeFromOriginalSourceFilename);
var softwareBitmap = await GetSoftwareBitmap(newFile);
await CropBitmap(newFile, softwareBitmap, boundingBox);
var croppedFile = await StorageFile.GetFileFromPathAsync(newFile.Path);
var croppedBitmap = await GetSoftwareBitmap(croppedFile);
await ScaleBitmap(croppedFile, croppedBitmap, width, height);
return newFile.Path;
}
/// <summary>
/// Uses the Microsoft Vision API to generate a picture that crops automatically to whatever size you choose.
/// </summary>
/// <param name="originalSourcePath">The original SourcePath to a file on Device OR An url to a picture</param>
/// <param name="width">Width of the cropped image</param>
/// <param name="height">Height of the cropped image</param>
/// <param name="addToFilename">What string should be after the originalSourcePath. if original is img20161203.jpg and addToFileName is -thumbnail then the outcome will be img20161203-thumbnail.jpg</param>
/// <param name="removeFromOriginalSourceFilename">a string that should be removed from original source ex. originalSourcepath = "Image-fullImage.jpg" removeFromOriginalSourceFilename = "-fullImage" the resulting path string will be "Image"+"addToFilename+".jpg"</param>
/// <returns></returns>
public async Task<string> SmartCrop(string originalSourcePath, int width, int height, string addToFilename, string removeFromOriginalSourceFilename = null) {
string newPath = null;
byte[] thumbNailByteArray=null;
if (originalSourcePath.IsUrl()) {
thumbNailByteArray = await VisionApi.GetThumbNail(originalSourcePath, width, height);
}else {
var downSampledPath = await FixMaxImageSize(originalSourcePath, 4000000);
var originalBytes = File.ReadAllBytes(downSampledPath);
thumbNailByteArray = await VisionApi.GetThumbNail(originalBytes, width, height);
}
newPath = SetupNewSourcePath(originalSourcePath,removeFromOriginalSourceFilename,addToFilename);
File.WriteAllBytes(newPath, thumbNailByteArray);
return newPath;
}
/// <summary>
/// Uses the Microsoft Vision API to generate a picture that crops automatically to whatever size you choose.
/// </summary>
/// <param name="originalSourcePath">The original SourcePath to a file on Device OR An url to a picture</param>
/// <param name="width">Width of the cropped image</param>
/// <param name="height">Height of the cropped image</param>
/// <returns>Byte array of new image</returns>
async public Task<byte[]> SmartCrop(string originalSourcePath, int width, int height) {
if (originalSourcePath.IsUrl()) {
return await VisionApi.GetThumbNail(originalSourcePath, width, height);
}
else {
var downSampledPath = await FixMaxImageSize(originalSourcePath, 4000000);
var originalBytes = File.ReadAllBytes(downSampledPath);
return await VisionApi.GetThumbNail(originalBytes, width, height);
}
}
/// <summary>
/// Uses the Microsoft Vision API to generate a picture that crops automatically to whatever size you choose.
/// </summary>
/// <param name="stream">Stream of an image that is used to send to Vision api</param>
/// <param name="width">Width of the cropped image</param>
/// <param name="height">Height of the cropped image</param>
/// <returns>Byte array of new image</returns>
async public Task<byte[]> SmartCrop(Stream stream, int width, int height) {
if (stream.Length > 4000000) {
throw new NotSupportedException("You are trying to SmartCrop a Stream that is bigger than 4Mb");
}
return await VisionApi.GetThumbNail(stream.ToByteArray(), width, height);
}
/// <summary>
/// Uses the Microsoft Vision API to generate a picture that crops automatically to whatever size you choose.
/// </summary>
/// <param name="stream">Stream of an image that is used to send to Vision api</param>
/// <param name="width">Width of the cropped image</param>
/// <param name="height">Height of the cropped image</param>
/// <param name="newFilePath">path to file that is going to be created</param>
/// <returns>The path to the cropped image</returns>
async public Task<string> SmartCrop(Stream stream, int width, int height, string newFilePath) {
if (stream.Length > 4000000) {
throw new NotSupportedException("You are trying to SmartCrop a Stream that is bigger than 4Mb");
}
var thumbNailByteArray = await VisionApi.GetThumbNail(stream.ToByteArray(), width, height);
File.WriteAllBytes(newFilePath, thumbNailByteArray);
return newFilePath;
}
/// <summary>
/// Checks if size of file is bigger than given maxBytes. If so it downsamples the image to the size of maxBytes.
/// </summary>
/// <param name="filePath">Path to file</param>
/// <param name="maxBytes">Max aloud bytes</param>
/// <returns>Path to file under given maxBytes or the filePath if filesize was smaller than given maxBytes</returns>
async public Task<string> FixMaxImageSize(string filePath, long maxBytes) {
var info = new FileInfo(filePath);
var length = info.Length;
if (length > maxBytes) {
var percentageToFit =(float) length / maxBytes;
var originalFile = await StorageFile.GetFileFromPathAsync(filePath);
var folder = await GetFolderFromStorageFile(originalFile);
var newFile =await folder.CreateFileAsync( SetupNewSourcePath(originalFile.Name,"","-smallerCopy"));
var softBitmap =await GetSoftwareBitmap(originalFile);
await ScaleBitmap(newFile, softBitmap, softBitmap.PixelWidth/percentageToFit,softBitmap.PixelHeight/percentageToFit);
return newFile.Path;
}
return filePath;
}
/// <summary>
/// Checks if size of file is bigger than given maxBytes. If so it downsamples the image to the size of maxBytes.
/// </summary>
/// <param name="stream">Stream </param>
/// <param name="maxBytes">Max aloud bytes</param>
/// <returns>Byte array of stream under given maxBytes, or the byte array of original stream if stream length was smaller than given maxBytes</returns>
async public Task<byte[]> FixMaxImageSize(Stream stream, long maxBytes) {
var length = stream.Length;
if (length > maxBytes) {
var percentageToFit = (float)length / maxBytes;
var scaledFile = await CreateTempFileScaled(stream,percentageToFit);
IBuffer buffer = await FileIO.ReadBufferAsync(scaledFile);
return buffer.ToArray();
}
return stream.ToByteArray();
}
async private Task<StorageFile> CreateTempFileScaled(Stream stream, float percentageToFit) {
var appFolder = ApplicationData.Current.TemporaryFolder;
var tempFile = await appFolder.CreateFileAsync(Guid.NewGuid() + ".jpg");
using (IRandomAccessStream str = await tempFile.OpenAsync(FileAccessMode.ReadWrite) ) {
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream());
var softBitmap = await decoder.GetSoftwareBitmapAsync();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, str);
encoder.SetSoftwareBitmap(softBitmap);
encoder.BitmapTransform.ScaledWidth = (uint)(softBitmap.PixelWidth/percentageToFit);
encoder.BitmapTransform.ScaledHeight = (uint)(softBitmap.PixelHeight/percentageToFit);
try {
await encoder.FlushAsync();
return tempFile;
}
catch (Exception err) {
throw new Exception("[CropImageImplementation] ScaleBitmap Could not scale Bitmap Message= " + err.Message);
}
}
}
#region Private
async private Task<StorageFile> MakeCopyOfFile(string originalSourcePath, string addToFilename, string removeFromOriginalSourceFilename) {
var originalFile = await StorageFile.GetFileFromPathAsync(originalSourcePath);
var newFileName = SetupNewSourcePath(originalFile.Name, removeFromOriginalSourceFilename, addToFilename);
var newPathToGeneratedFile = SetupNewSourcePath(originalSourcePath, removeFromOriginalSourceFilename, addToFilename);
return await originalFile.CopyAsync(await GetFolderFromStorageFile(originalFile), newFileName, NameCollisionOption.ReplaceExisting);
}
async private Task<IStorageFolder> GetFolderFromStorageFile(StorageFile originalFile) {
return await StorageFolder.GetFolderFromPathAsync(originalFile.Path.Replace(originalFile.Name, ""));
}
async private Task ScaleBitmap(StorageFile croppedFile, SoftwareBitmap croppedBitmap,float width,float height) {
using (IRandomAccessStream newStream = await croppedFile.OpenAsync(FileAccessMode.ReadWrite)) {
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, newStream);
encoder.SetSoftwareBitmap(croppedBitmap);
encoder.BitmapTransform.ScaledWidth = (uint)width;
encoder.BitmapTransform.ScaledHeight = (uint)height;
try {
await encoder.FlushAsync();
}
catch (Exception err) {
throw new Exception("[CropImageImplementation] ScaleBitmap Could not scale Bitmap Message= " + err.Message);
}
}
}
async private Task CropBitmap(StorageFile newFile, SoftwareBitmap softwareBitmap, BoundingBox boundingBox) {
using (IRandomAccessStream newStream = await newFile.OpenAsync(FileAccessMode.ReadWrite)) {
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, newStream);
encoder.SetSoftwareBitmap(softwareBitmap);
encoder.BitmapTransform.Bounds = new BitmapBounds() { X = (uint)boundingBox.Left, Width = (uint)boundingBox.Width, Y = (uint)boundingBox.Top, Height = (uint)boundingBox.Height };
try {
await encoder.FlushAsync();
}
catch (Exception err) {
throw new Exception("[CropImageImplementation] CropBitmap Could not Crop Image Message= " + err.Message);
}
}
}
async private Task<SoftwareBitmap> GetSoftwareBitmap(StorageFile newFile) {
SoftwareBitmap softwareBitmap;
using (IRandomAccessStream stream = await newFile.OpenAsync(FileAccessMode.Read)) {
// Create the decoder from the stream
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
// Get the SoftwareBitmap representation of the file
softwareBitmap = await decoder.GetSoftwareBitmapAsync();
}
return softwareBitmap;
}
private string SetupNewSourcePath(string originalSourcePath, string removeFromOriginalSourceFilename, string addToFilename) {
var orSourcePath = originalSourcePath;
if (!string.IsNullOrEmpty(removeFromOriginalSourceFilename)) {
orSourcePath = orSourcePath.Replace(removeFromOriginalSourceFilename, "");
}
var extension = orSourcePath.Substring(orSourcePath.LastIndexOf("."));
return orSourcePath.Replace(extension, addToFilename + extension);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace PatternsIntro.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Memcache.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCloudMemcacheClientTest
{
[xunit::FactAttribute]
public void GetInstanceRequestObject()
{
moq::Mock<CloudMemcache.CloudMemcacheClient> mockGrpcClient = new moq::Mock<CloudMemcache.CloudMemcacheClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
DisplayName = "display_name137f65c2",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AuthorizedNetwork = "authorized_network63563381",
Zones = { "zones3641f926", },
NodeCount = -1659500730,
NodeConfig = new Instance.Types.NodeConfig(),
MemcacheVersion = MemcacheVersion.Memcache15,
Parameters = new MemcacheParameters(),
MemcacheNodes =
{
new Instance.Types.Node(),
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = Instance.Types.State.Deleting,
MemcacheFullVersion = "memcache_full_version4b648a5f",
InstanceMessages =
{
new Instance.Types.InstanceMessage(),
},
DiscoveryEndpoint = "discovery_endpointe07f14c7",
};
mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudMemcacheClient client = new CloudMemcacheClientImpl(mockGrpcClient.Object, null);
Instance response = client.GetInstance(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceRequestObjectAsync()
{
moq::Mock<CloudMemcache.CloudMemcacheClient> mockGrpcClient = new moq::Mock<CloudMemcache.CloudMemcacheClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
DisplayName = "display_name137f65c2",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AuthorizedNetwork = "authorized_network63563381",
Zones = { "zones3641f926", },
NodeCount = -1659500730,
NodeConfig = new Instance.Types.NodeConfig(),
MemcacheVersion = MemcacheVersion.Memcache15,
Parameters = new MemcacheParameters(),
MemcacheNodes =
{
new Instance.Types.Node(),
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = Instance.Types.State.Deleting,
MemcacheFullVersion = "memcache_full_version4b648a5f",
InstanceMessages =
{
new Instance.Types.InstanceMessage(),
},
DiscoveryEndpoint = "discovery_endpointe07f14c7",
};
mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudMemcacheClient client = new CloudMemcacheClientImpl(mockGrpcClient.Object, null);
Instance responseCallSettings = await client.GetInstanceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Instance responseCancellationToken = await client.GetInstanceAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstance()
{
moq::Mock<CloudMemcache.CloudMemcacheClient> mockGrpcClient = new moq::Mock<CloudMemcache.CloudMemcacheClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
DisplayName = "display_name137f65c2",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AuthorizedNetwork = "authorized_network63563381",
Zones = { "zones3641f926", },
NodeCount = -1659500730,
NodeConfig = new Instance.Types.NodeConfig(),
MemcacheVersion = MemcacheVersion.Memcache15,
Parameters = new MemcacheParameters(),
MemcacheNodes =
{
new Instance.Types.Node(),
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = Instance.Types.State.Deleting,
MemcacheFullVersion = "memcache_full_version4b648a5f",
InstanceMessages =
{
new Instance.Types.InstanceMessage(),
},
DiscoveryEndpoint = "discovery_endpointe07f14c7",
};
mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudMemcacheClient client = new CloudMemcacheClientImpl(mockGrpcClient.Object, null);
Instance response = client.GetInstance(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceAsync()
{
moq::Mock<CloudMemcache.CloudMemcacheClient> mockGrpcClient = new moq::Mock<CloudMemcache.CloudMemcacheClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
DisplayName = "display_name137f65c2",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AuthorizedNetwork = "authorized_network63563381",
Zones = { "zones3641f926", },
NodeCount = -1659500730,
NodeConfig = new Instance.Types.NodeConfig(),
MemcacheVersion = MemcacheVersion.Memcache15,
Parameters = new MemcacheParameters(),
MemcacheNodes =
{
new Instance.Types.Node(),
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = Instance.Types.State.Deleting,
MemcacheFullVersion = "memcache_full_version4b648a5f",
InstanceMessages =
{
new Instance.Types.InstanceMessage(),
},
DiscoveryEndpoint = "discovery_endpointe07f14c7",
};
mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudMemcacheClient client = new CloudMemcacheClientImpl(mockGrpcClient.Object, null);
Instance responseCallSettings = await client.GetInstanceAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Instance responseCancellationToken = await client.GetInstanceAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstanceResourceNames()
{
moq::Mock<CloudMemcache.CloudMemcacheClient> mockGrpcClient = new moq::Mock<CloudMemcache.CloudMemcacheClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
DisplayName = "display_name137f65c2",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AuthorizedNetwork = "authorized_network63563381",
Zones = { "zones3641f926", },
NodeCount = -1659500730,
NodeConfig = new Instance.Types.NodeConfig(),
MemcacheVersion = MemcacheVersion.Memcache15,
Parameters = new MemcacheParameters(),
MemcacheNodes =
{
new Instance.Types.Node(),
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = Instance.Types.State.Deleting,
MemcacheFullVersion = "memcache_full_version4b648a5f",
InstanceMessages =
{
new Instance.Types.InstanceMessage(),
},
DiscoveryEndpoint = "discovery_endpointe07f14c7",
};
mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudMemcacheClient client = new CloudMemcacheClientImpl(mockGrpcClient.Object, null);
Instance response = client.GetInstance(request.InstanceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceResourceNamesAsync()
{
moq::Mock<CloudMemcache.CloudMemcacheClient> mockGrpcClient = new moq::Mock<CloudMemcache.CloudMemcacheClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
DisplayName = "display_name137f65c2",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AuthorizedNetwork = "authorized_network63563381",
Zones = { "zones3641f926", },
NodeCount = -1659500730,
NodeConfig = new Instance.Types.NodeConfig(),
MemcacheVersion = MemcacheVersion.Memcache15,
Parameters = new MemcacheParameters(),
MemcacheNodes =
{
new Instance.Types.Node(),
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = Instance.Types.State.Deleting,
MemcacheFullVersion = "memcache_full_version4b648a5f",
InstanceMessages =
{
new Instance.Types.InstanceMessage(),
},
DiscoveryEndpoint = "discovery_endpointe07f14c7",
};
mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudMemcacheClient client = new CloudMemcacheClientImpl(mockGrpcClient.Object, null);
Instance responseCallSettings = await client.GetInstanceAsync(request.InstanceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Instance responseCancellationToken = await client.GetInstanceAsync(request.InstanceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox.ModAPI;
using VRage;
using VRage.Game.ModAPI;
using VRageMath;
using VRage.ModAPI;
using VRage.Game.Entity;
using Sandbox.Common.ObjectBuilders;
using Sandbox.Game.Entities;
using Sandbox.Game;
using Sandbox.Definitions;
using Ingame = Sandbox.ModAPI.Ingame;
using VRage.Game;
using NaniteConstructionSystem.Particles;
using NaniteConstructionSystem.Extensions;
namespace NaniteConstructionSystem.Entities.Targets
{
public class NaniteFloatingTarget
{
public int ParticleCount { get; set; }
public double StartTime { get; set; }
public double CarryTime { get; set; }
public double LastUpdate { get; set; }
}
public class NaniteFloatingTargets : NaniteTargetBlocksBase
{
public override string TargetName
{
get { return "Cleanup"; }
}
private HashSet<IMyEntity> m_entities = new HashSet<IMyEntity>();
private Dictionary<IMyEntity, NaniteFloatingTarget> m_targetTracker;
private float m_carryVolume = 10f;
private float m_maxDistance = 500f;
public NaniteFloatingTargets(NaniteConstructionBlock constructionBlock) : base(constructionBlock)
{
m_targetTracker = new Dictionary<IMyEntity, NaniteFloatingTarget>();
m_carryVolume = NaniteConstructionManager.Settings.CleanupCarryVolume;
m_maxDistance = NaniteConstructionManager.Settings.CleanupMaxDistance;
}
public override void FindTargets(ref Dictionary<string, int> available)
{
if (!IsEnabled())
return;
if (TargetList.Count >= GetMaximumTargets())
{
if (PotentialTargetList.Count > 0)
m_lastInvalidTargetReason = "Maximum targets reached. Add more upgrades!";
return;
}
using (Lock.AcquireExclusiveUsing())
{
for(int r = PotentialTargetList.Count - 1; r >= 0; r--)
{
if (m_constructionBlock.IsUserDefinedLimitReached())
{
m_lastInvalidTargetReason = "User defined maximum nanite limit reached";
return;
}
var item = (IMyEntity)PotentialTargetList[r];
if (TargetList.Contains(item))
continue;
if (item.Closed)
{
PotentialTargetList.RemoveAt(r);
continue;
}
var blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid);
bool found = false;
foreach (var block in blockList)
{
if (block.Targets.First(x => x is NaniteFloatingTargets).TargetList.Contains(item))
{
found = true;
break;
}
}
if (found)
{
m_lastInvalidTargetReason = "Another factory has this block as a target";
continue;
}
if (Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), item.GetPosition()) < m_maxDistance * m_maxDistance &&
NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this))
{
TargetList.Add(item);
Logging.Instance.WriteLine(string.Format("ADDING Floating Object Target: conid={0} type={1} entityID={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, item.GetType().Name, item.EntityId, item.GetPosition()));
if (TargetList.Count >= GetMaximumTargets())
break;
}
}
}
}
public override int GetMaximumTargets()
{
MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock;
return (int)Math.Min(NaniteConstructionManager.Settings.CleanupNanitesNoUpgrade + (block.UpgradeValues["CleanupNanites"] * NaniteConstructionManager.Settings.CleanupNanitesPerUpgrade), NaniteConstructionManager.Settings.CleanupMaxStreams);
}
public override float GetPowerUsage()
{
MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock;
return Math.Max(1, NaniteConstructionManager.Settings.CleanupPowerPerStream - (int)(block.UpgradeValues["PowerNanites"] * NaniteConstructionManager.Settings.PowerDecreasePerUpgrade));
}
public override float GetMinTravelTime()
{
MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock;
return Math.Max(1f, NaniteConstructionManager.Settings.CleanupMinTravelTime - (block.UpgradeValues["SpeedNanites"] * NaniteConstructionManager.Settings.MinTravelTimeReductionPerUpgrade));
}
public override float GetSpeed()
{
MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock;
return NaniteConstructionManager.Settings.CleanupDistanceDivisor + (block.UpgradeValues["SpeedNanites"] * (float)NaniteConstructionManager.Settings.SpeedIncreasePerUpgrade);
}
public override bool IsEnabled()
{
bool result = true;
if (!((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock).Enabled ||
!((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock).IsFunctional ||
m_constructionBlock.ConstructionBlock.CustomName.ToLower().Contains("NoCleanup".ToLower()))
result = false;
if (NaniteConstructionManager.TerminalSettings.ContainsKey(m_constructionBlock.ConstructionBlock.EntityId))
{
if (!NaniteConstructionManager.TerminalSettings[m_constructionBlock.ConstructionBlock.EntityId].AllowCleanup)
return false;
}
return result;
}
public override void Update()
{
foreach (var item in m_targetList.ToList())
{
ProcessItem(item);
}
}
private void ProcessItem(object target)
{
var floating = target as IMyEntity;
if (floating == null)
return;
if (Sync.IsServer)
{
if (!IsEnabled())
{
Logging.Instance.WriteLine("CANCELLING Cleanup Target due to being disabled");
CancelTarget(floating);
return;
}
if (m_constructionBlock.FactoryState != NaniteConstructionBlock.FactoryStates.Active)
return;
if(!NaniteConstructionPower.HasRequiredPowerForCurrentTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock))
{
Logging.Instance.WriteLine("CANCELLING Cleanup Target due to power shortage");
CancelTarget(floating);
return;
}
if(floating.Closed)
{
CompleteTarget(floating);
return;
}
if (!m_targetTracker.ContainsKey(floating))
{
m_constructionBlock.SendAddTarget(floating);
}
if(m_targetTracker.ContainsKey(floating))
{
var trackedItem = m_targetTracker[floating];
if (MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - trackedItem.StartTime >= trackedItem.CarryTime &&
MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - trackedItem.LastUpdate > 2000)
{
trackedItem.LastUpdate = MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds;
if (!TransferFromTarget((IMyEntity)target))
{
Logging.Instance.WriteLine("CANCELLING Cleanup Target due to insufficient storage");
CancelTarget(floating);
}
}
}
}
CreateFloatingParticle(floating);
}
private void OpenBag(IMyEntity bagEntity)
{
try
{
MyInventoryBagEntity bag = bagEntity as MyInventoryBagEntity;
if (bag == null)
return;
foreach (var item in bag.GetInventory().GetItems().ToList())
{
MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(item.Amount, item.Content), bagEntity.WorldMatrix.Translation, bagEntity.WorldMatrix.Forward, bagEntity.WorldMatrix.Up);
}
bagEntity.Close();
}
catch(Exception ex)
{
Logging.Instance.WriteLine(string.Format("OpenBag Error(): {0}", ex.ToString()));
}
}
private void OpenCharacter(IMyEntity charEntity)
{
try
{
MyEntity entity = (MyEntity)charEntity;
charEntity.Close();
}
catch(Exception ex)
{
Logging.Instance.WriteLine(string.Format("OpenCharacter() Error: {0}", ex.ToString()));
}
}
private bool TransferFromTarget(IMyEntity target, bool transfer=true)
{
if(target is IMyCharacter)
{
if (transfer)
{
MyAPIGateway.Utilities.InvokeOnGameThread(() =>
{
OpenCharacter(target);
});
}
return true;
}
if(target is MyInventoryBagEntity)
{
if (transfer)
{
MyAPIGateway.Utilities.InvokeOnGameThread(() =>
{
OpenBag(target);
});
}
return true;
}
MyFloatingObject floating = (MyFloatingObject)target;
MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory();
var def = MyDefinitionManager.Static.GetPhysicalItemDefinition(new VRage.Game.MyDefinitionId(floating.Item.Content.TypeId, floating.Item.Content.SubtypeId));
float amount = GetNaniteInventoryAmountThatFits(target, (MyCubeBlock)m_constructionBlock.ConstructionBlock);
if ((int)amount > 0 || MyAPIGateway.Session.CreativeMode)
{
if (MyAPIGateway.Session.CreativeMode)
m_carryVolume = 10000f;
if ((int)amount > 1 && (amount / def.Volume) > m_carryVolume)
amount = m_carryVolume / def.Volume;
if ((int)amount < 1)
amount = 1f;
if(transfer)
targetInventory.PickupItem(floating, (int)amount);
return true;
}
return FindFreeCargo(target, (MyCubeBlock)m_constructionBlock.ConstructionBlock, transfer);
}
private bool FindFreeCargo(IMyEntity target, MyCubeBlock startBlock, bool transfer)
{
var list = Conveyor.GetConveyorListFromEntity(m_constructionBlock.ConstructionBlock);
if (list == null)
return false;
List<MyInventory> inventoryList = new List<MyInventory>();
foreach(var item in list)
{
IMyEntity entity;
if (MyAPIGateway.Entities.TryGetEntityById(item, out entity))
{
if (!(entity is IMyCubeBlock))
continue;
if (entity is Ingame.IMyRefinery || entity is Ingame.IMyAssembler)
continue;
MyCubeBlock block = (MyCubeBlock)entity;
if (!block.HasInventory)
continue;
inventoryList.Add(block.GetInventory());
}
}
MyFloatingObject floating = (MyFloatingObject)target;
float amount = 0f;
MyInventory targetInventory = null;
foreach (var item in inventoryList.OrderByDescending(x => (float)x.MaxVolume - (float)x.CurrentVolume))
{
amount = GetNaniteInventoryAmountThatFits(target, (MyCubeBlock)item.Owner);
if ((int)amount == 0)
continue;
targetInventory = item;
break;
}
if ((int)amount == 0)
return false;
var def = MyDefinitionManager.Static.GetPhysicalItemDefinition(new VRage.Game.MyDefinitionId(floating.Item.Content.TypeId, floating.Item.Content.SubtypeId));
if ((int)amount > 1 && (amount / def.Volume) > m_carryVolume)
amount = m_carryVolume / def.Volume;
if ((int)amount < 1)
amount = 1f;
if (transfer)
targetInventory.PickupItem(floating, (int)amount);
return true;
}
private float GetNaniteInventoryAmountThatFits(IMyEntity target, MyCubeBlock block)
{
if (!block.HasInventory)
return 0f;
MyFloatingObject floating = (MyFloatingObject)target;
var def = MyDefinitionManager.Static.GetPhysicalItemDefinition(new VRage.Game.MyDefinitionId(floating.Item.Content.TypeId, floating.Item.Content.SubtypeId));
MyInventory inventory = block.GetInventory();
MyFixedPoint amountFits = inventory.ComputeAmountThatFits(new VRage.Game.MyDefinitionId(floating.Item.Content.TypeId, floating.Item.Content.SubtypeId));
//Logging.Instance.WriteLine(string.Format("AmountFits: {0} - {1}", amountFits, def.Volume));
//float amount;
/*
if (amountFits * def.Volume > 1)
{
amount = 1f / def.Volume;
}
else
amount = (float)amountFits;
*/
return (float)amountFits;
}
public void CancelTarget(IMyEntity obj)
{
Logging.Instance.WriteLine(string.Format("CANCELLING Floating Object Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, obj.GetType().Name, obj.EntityId, obj.GetPosition()));
if (Sync.IsServer)
m_constructionBlock.SendCancelTarget(obj);
m_constructionBlock.ParticleManager.CancelTarget(obj);
if (m_targetTracker.ContainsKey(obj))
m_targetTracker.Remove(obj);
Remove(obj);
}
public void CancelTarget(long entityId)
{
m_constructionBlock.ParticleManager.CancelTarget(entityId);
foreach (var item in m_targetTracker.ToList())
{
if (item.Key.EntityId == entityId)
{
m_targetTracker.Remove(item.Key);
}
}
foreach (IMyEntity item in TargetList.Where(x => ((IMyEntity)x).EntityId == entityId))
Logging.Instance.WriteLine(string.Format("COMPLETING Floating Object Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, item.EntityId, item.GetPosition()));
TargetList.RemoveAll(x => ((IMyEntity)x).EntityId == entityId);
PotentialTargetList.RemoveAll(x => ((IMyEntity)x).EntityId == entityId);
}
public override void CancelTarget(object obj)
{
var target = obj as IMyEntity;
if (target == null)
return;
CancelTarget(target);
}
public override void CompleteTarget(object obj)
{
var target = obj as IMyEntity;
if (target == null)
return;
CompleteTarget(target);
}
public void CompleteTarget(IMyEntity obj)
{
Logging.Instance.WriteLine(string.Format("COMPLETING Floating Object Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, obj.GetType().Name, obj.EntityId, obj.GetPosition()));
if (Sync.IsServer)
{
m_constructionBlock.SendCompleteTarget(obj);
}
m_constructionBlock.ParticleManager.CompleteTarget(obj);
if(m_targetTracker.ContainsKey(obj))
m_targetTracker.Remove(obj);
Remove(obj);
}
public void CompleteTarget(long entityId)
{
m_constructionBlock.ParticleManager.CompleteTarget(entityId);
foreach (var item in m_targetTracker.ToList())
{
if (item.Key.EntityId == entityId)
{
m_targetTracker.Remove(item.Key);
}
}
foreach(IMyEntity item in TargetList.Where(x => ((IMyEntity)x).EntityId == entityId))
Logging.Instance.WriteLine(string.Format("COMPLETING Floating Object Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, item.GetType().Name, item.EntityId, item.GetPosition()));
TargetList.RemoveAll(x => ((IMyEntity)x).EntityId == entityId);
PotentialTargetList.RemoveAll(x => ((IMyEntity)x).EntityId == entityId);
}
private void CreateFloatingParticle(IMyEntity target)
{
double distance = Vector3D.Distance(m_constructionBlock.ConstructionBlock.GetPosition(), target.GetPosition());
int time = (int)Math.Max(GetMinTravelTime() * 1000f, (distance / GetSpeed()) * 1000f);
// This should be moved somewhere else. It initializes a tracker
if (!m_targetTracker.ContainsKey(target))
{
NaniteFloatingTarget floatingTarget = new NaniteFloatingTarget();
floatingTarget.ParticleCount = 0;
floatingTarget.StartTime = MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds;
floatingTarget.LastUpdate = MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds;
floatingTarget.CarryTime = time - 1000;
m_targetTracker.Add(target, floatingTarget);
}
if (NaniteParticleManager.TotalParticleCount > NaniteParticleManager.MaxTotalParticles)
return;
m_targetTracker[target].ParticleCount++;
int size = (int)Math.Max(60f, NaniteParticleManager.TotalParticleCount);
if ((float)m_targetTracker[target].ParticleCount / size < 1f)
return;
m_targetTracker[target].ParticleCount = 0;
// Create Particle
Vector4 startColor = new Vector4(0.75f, 0.75f, 0.0f, 0.75f);
Vector4 endColor = new Vector4(0.20f, 0.20f, 0.0f, 0.75f);
m_constructionBlock.ParticleManager.AddParticle(startColor, endColor, GetMinTravelTime() * 1000f, GetSpeed(), target);
}
public override void ParallelUpdate(List<IMyCubeGrid> gridList, List<IMySlimBlock> blocks)
{
using (m_lock.AcquireExclusiveUsing())
{
PotentialTargetList.Clear();
}
m_entities.Clear();
try
{
MyAPIGateway.Entities.GetEntities(m_entities, x => x is IMyFloatingObject || x is MyInventoryBagEntity || x is IMyCharacter);
}
catch
{
Logging.Instance.WriteLine(string.Format("Error getting entities, skipping"));
return;
}
if (!IsEnabled())
return;
foreach (var item in m_entities)
{
if(item is IMyCharacter)
{
var charBuilder = (MyObjectBuilder_Character)item.GetObjectBuilder();
if (charBuilder.LootingCounter <= 0f)
continue;
}
if(Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), item.GetPosition()) < m_maxDistance * m_maxDistance &&
TransferFromTarget(item, false))
{
using(m_lock.AcquireExclusiveUsing())
PotentialTargetList.Add(item);
}
}
}
}
}
| |
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime.MembershipService;
using Xunit;
using NSubstitute;
using Orleans.Runtime;
using System;
using Orleans;
using Xunit.Abstractions;
using System.Linq;
using TestExtensions;
using System.Collections.Generic;
using System.Threading;
using System.Collections.Concurrent;
using NonSilo.Tests.Utilities;
namespace NonSilo.Tests.Membership
{
/// <summary>
/// Tests for <see cref="MembershipTableManager"/>
/// </summary>
[TestCategory("BVT"), TestCategory("Membership")]
public class MembershipTableManagerTests
{
private readonly ITestOutputHelper output;
private readonly LoggerFactory loggerFactory;
private readonly ILocalSiloDetails localSiloDetails;
private readonly SiloAddress localSilo;
private readonly IFatalErrorHandler fatalErrorHandler;
private readonly IMembershipGossiper membershipGossiper;
private readonly SiloLifecycleSubject lifecycle;
public MembershipTableManagerTests(ITestOutputHelper output)
{
this.output = output;
this.loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(this.output) });
this.localSiloDetails = Substitute.For<ILocalSiloDetails>();
this.localSilo = Silo("127.0.0.1:100@100");
this.localSiloDetails.SiloAddress.Returns(this.localSilo);
this.localSiloDetails.DnsHostName.Returns("MyServer11");
this.localSiloDetails.Name.Returns(Guid.NewGuid().ToString("N"));
this.fatalErrorHandler = Substitute.For<IFatalErrorHandler>();
this.fatalErrorHandler.IsUnexpected(default).ReturnsForAnyArgs(true);
this.membershipGossiper = Substitute.For<IMembershipGossiper>();
this.lifecycle = new SiloLifecycleSubject(this.loggerFactory.CreateLogger<SiloLifecycleSubject>());
}
/// <summary>
/// Tests <see cref="MembershipTableManager"/> behavior around silo startup for a fresh cluster.
/// </summary>
[Fact]
public async Task MembershipTableManager_NewCluster()
{
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"));
await this.BasicScenarioTest(membershipTable, gracefulShutdown: true);
}
/// <summary>
/// Tests <see cref="MembershipTableManager"/> behavior around silo startup when there is an
/// existing cluster.
/// </summary>
[Fact]
public async Task MembershipTableManager_ExistingCluster()
{
var otherSilos = new[]
{
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:300@100"), SiloStatus.ShuttingDown),
Entry(Silo("127.0.0.1:400@100"), SiloStatus.Joining),
Entry(Silo("127.0.0.1:500@100"), SiloStatus.Dead),
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
await this.BasicScenarioTest(membershipTable, gracefulShutdown: false);
}
private async Task BasicScenarioTest(InMemoryMembershipTable membershipTable, bool gracefulShutdown = true)
{
var timers = new List<DelegateAsyncTimer>();
var timerCalls = new ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>();
var timerFactory = new DelegateAsyncTimerFactory(
(period, name) =>
{
var timer = new DelegateAsyncTimer(
overridePeriod =>
{
var task = new TaskCompletionSource<bool>();
timerCalls.Enqueue((overridePeriod, task));
return task.Task;
});
timers.Add(timer);
return timer;
});
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: timerFactory,
this.lifecycle);
// Validate that the initial snapshot is valid and contains the local silo.
var initialSnapshot = manager.MembershipTableSnapshot;
Assert.NotNull(initialSnapshot);
Assert.NotNull(initialSnapshot.Entries);
var localSiloEntry = initialSnapshot.Entries[this.localSilo];
Assert.Equal(SiloStatus.Created, localSiloEntry.Status);
Assert.Equal(this.localSiloDetails.Name, localSiloEntry.SiloName);
Assert.Equal(this.localSiloDetails.DnsHostName, localSiloEntry.HostName);
Assert.Equal(SiloStatus.Created, manager.CurrentStatus);
Assert.NotNull(manager.MembershipTableUpdates);
var changes = manager.MembershipTableUpdates;
var currentEnumerator = changes.GetAsyncEnumerator();
Assert.True(currentEnumerator.MoveNextAsync().Result);
Assert.Equal(currentEnumerator.Current.Version, manager.MembershipTableSnapshot.Version);
Assert.Empty(membershipTable.Calls);
// All of these checks were performed before any lifecycle methods have a chance to run.
// This is in order to verify that a service accessing membership in its constructor will
// see the correct results regardless of initialization order.
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
var calls = membershipTable.Calls;
Assert.NotEmpty(calls);
Assert.True(calls.Count >= 2);
Assert.Equal(nameof(IMembershipTable.InitializeMembershipTable), calls[0].Method);
Assert.Equal(nameof(IMembershipTable.ReadAll), calls[1].Method);
// During initialization, a first read from the table will be performed, transitioning
// membership to a valid version.currentEnumerator = changes.GetAsyncEnumerator();
currentEnumerator = changes.GetAsyncEnumerator();
Assert.True(currentEnumerator.MoveNextAsync().Result);
var update1 = currentEnumerator.Current;
// Transition to joining.
this.membershipGossiper.ClearReceivedCalls();
await manager.UpdateStatus(SiloStatus.Joining);
await this.membershipGossiper.ReceivedWithAnyArgs().GossipToRemoteSilos(default, default, default, default);
Assert.Equal(SiloStatus.Joining, manager.CurrentStatus);
localSiloEntry = manager.MembershipTableSnapshot.Entries[this.localSilo];
Assert.Equal(SiloStatus.Joining, localSiloEntry.Status);
// An update should have been issued.
currentEnumerator = changes.GetAsyncEnumerator();
Assert.True(currentEnumerator.MoveNextAsync().Result);
Assert.NotEqual(update1.Version, manager.MembershipTableSnapshot.Version);
var update2 = currentEnumerator.Current;
Assert.Equal(update2.Version, manager.MembershipTableSnapshot.Version);
var entry = Assert.Single(update2.Entries, e => e.Key.Equals(this.localSilo));
Assert.Equal(this.localSilo, entry.Key);
Assert.Equal(this.localSilo, entry.Value.SiloAddress);
Assert.Equal(SiloStatus.Joining, entry.Value.Status);
calls = membershipTable.Calls.Skip(2).ToList();
Assert.NotEmpty(calls);
Assert.Contains(calls, call => call.Method.Equals(nameof(IMembershipTable.InsertRow)));
Assert.Contains(calls, call => call.Method.Equals(nameof(IMembershipTable.ReadAll)));
{
// Check that a timer is being requested and that after it expires a call to
// refresh the membership table is made.
Assert.True(timerCalls.TryDequeue(out var timer));
membershipTable.ClearCalls();
timer.Completion.TrySetResult(true);
while (membershipTable.Calls.Count == 0) await Task.Delay(10);
Assert.Contains(membershipTable.Calls, c => c.Method.Equals(nameof(IMembershipTable.ReadAll)));
}
var cts = new CancellationTokenSource();
if (!gracefulShutdown) cts.Cancel();
Assert.Equal(0, timers.First().DisposedCounter);
var stopped = this.lifecycle.OnStop(cts.Token);
// Complete any timers that were waiting.
while (timerCalls.TryDequeue(out var t)) t.Completion.TrySetResult(false);
await stopped;
Assert.Equal(1, timers.First().DisposedCounter);
this.fatalErrorHandler.DidNotReceiveWithAnyArgs().OnFatalException(default, default, default);
}
/// <summary>
/// Tests <see cref="MembershipTableManager"/> behavior around silo startup when there is an
/// existing cluster and this silo has been restarted (there is an existing entry with an
/// older generation).
/// </summary>
[Fact]
public async Task MembershipTableManager_Restarted()
{
// The table includes a predecessor which is still marked as active
// This can happen if a node restarts quickly.
var predecessor = Entry(Silo("127.0.0.1:100@1"), SiloStatus.Active);
var otherSilos = new[]
{
predecessor,
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:300@100"), SiloStatus.ShuttingDown),
Entry(Silo("127.0.0.1:400@100"), SiloStatus.Joining),
Entry(Silo("127.0.0.1:500@100"), SiloStatus.Dead),
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
this.lifecycle);
// Validate that the initial snapshot is valid and contains the local silo.
var snapshot = manager.MembershipTableSnapshot;
Assert.NotNull(snapshot);
Assert.NotNull(snapshot.Entries);
var localSiloEntry = snapshot.Entries[this.localSilo];
Assert.Equal(SiloStatus.Created, localSiloEntry.Status);
Assert.Equal(this.localSiloDetails.Name, localSiloEntry.SiloName);
Assert.Equal(this.localSiloDetails.DnsHostName, localSiloEntry.HostName);
Assert.Equal(SiloStatus.Created, manager.CurrentStatus);
Assert.NotNull(manager.MembershipTableUpdates);
var membershipUpdates = manager.MembershipTableUpdates.GetAsyncEnumerator();
Assert.True(membershipUpdates.MoveNextAsync().Result);
var firstSnapshot = membershipUpdates.Current;
Assert.Equal(firstSnapshot.Version, manager.MembershipTableSnapshot.Version);
Assert.Empty(membershipTable.Calls);
// All of these checks were performed before any lifecycle methods have a chance to run.
// This is in order to verify that a service accessing membership in its constructor will
// see the correct results regardless of initialization order.
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
var calls = membershipTable.Calls;
Assert.NotEmpty(calls);
Assert.True(calls.Count >= 2);
Assert.Equal(nameof(IMembershipTable.InitializeMembershipTable), calls[0].Method);
Assert.Contains(calls, call => call.Method.Equals(nameof(IMembershipTable.ReadAll)));
// During initialization, a first read from the table will be performed, transitioning
// membership to a valid version.Assert.True(membershipUpdates.MoveNextAsync().Result);
Assert.True(membershipUpdates.MoveNextAsync().Result);
var update1 = membershipUpdates.Current;
// Transition to joining.
await manager.UpdateStatus(SiloStatus.Joining);
snapshot = manager.MembershipTableSnapshot;
Assert.Equal(SiloStatus.Joining, manager.CurrentStatus);
Assert.Equal(SiloStatus.Joining, snapshot.Entries[localSilo].Status);
Assert.True(membershipUpdates.MoveNextAsync().Result);
Assert.True(membershipUpdates.MoveNextAsync().Result);
Assert.Equal(membershipUpdates.Current.Version, manager.MembershipTableSnapshot.Version);
// The predecessor should have been marked dead during startup.
Assert.Equal(SiloStatus.Active, update1.GetSiloStatus(predecessor.SiloAddress));
var latest = membershipUpdates.Current;
Assert.Equal(SiloStatus.Dead, latest.GetSiloStatus(predecessor.SiloAddress));
var entry = Assert.Single(latest.Entries, e => e.Key.Equals(this.localSilo));
Assert.Equal(this.localSilo, entry.Key);
Assert.Equal(this.localSilo, entry.Value.SiloAddress);
Assert.Equal(SiloStatus.Joining, entry.Value.Status);
calls = membershipTable.Calls.Skip(2).ToList();
Assert.NotEmpty(calls);
Assert.Contains(calls, call => call.Method.Equals(nameof(IMembershipTable.InsertRow)));
Assert.Contains(calls, call => call.Method.Equals(nameof(IMembershipTable.ReadAll)));
await this.lifecycle.OnStop();
this.fatalErrorHandler.DidNotReceiveWithAnyArgs().OnFatalException(default, default, default);
}
/// <summary>
/// Tests <see cref="MembershipTableManager"/> behavior around silo startup when there is an
/// existing cluster and this silo has already been superseded by a newer iteration.
/// </summary>
[Fact]
public async Task MembershipTableManager_Superseded()
{
// The table includes a sucessor to this silo.
var successor = Entry(Silo("127.0.0.1:100@200"), SiloStatus.Active);
var otherSilos = new[]
{
successor,
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:300@100"), SiloStatus.ShuttingDown),
Entry(Silo("127.0.0.1:400@100"), SiloStatus.Joining),
Entry(Silo("127.0.0.1:500@100"), SiloStatus.Dead),
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
// Silo should kill itself during the joining phase
await manager.UpdateStatus(SiloStatus.Joining);
this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default);
await this.lifecycle.OnStop();
}
/// <summary>
/// Tests <see cref="MembershipTableManager"/> behavior around silo startup when there is an
/// existing cluster and this silo has already been declared dead.
/// Note that this should never happen in the way tested here - the silo should not be known
/// to other silos before it starts up. Still, the case is covered by the manager.
/// </summary>
[Fact]
public async Task MembershipTableManager_AlreadyDeclaredDead()
{
var otherSilos = new[]
{
Entry(this.localSilo, SiloStatus.Dead),
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:300@100"), SiloStatus.ShuttingDown),
Entry(Silo("127.0.0.1:400@100"), SiloStatus.Joining),
Entry(Silo("127.0.0.1:500@100"), SiloStatus.Dead),
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
// Silo should kill itself during the joining phase
await manager.UpdateStatus(SiloStatus.Joining);
this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default);
var cts = new CancellationTokenSource();
cts.Cancel();
await this.lifecycle.OnStop(cts.Token);
}
/// <summary>
/// Tests <see cref="MembershipTableManager"/> behavior when there is an
/// existing cluster and this silo is declared dead some time after updating its status to joining.
/// </summary>
[Fact]
public async Task MembershipTableManager_DeclaredDead_AfterJoining()
{
var otherSilos = new[]
{
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active)
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
siloLifecycle: this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
// Silo should kill itself during the joining phase
await manager.UpdateStatus(SiloStatus.Joining);
this.fatalErrorHandler.DidNotReceiveWithAnyArgs().OnFatalException(default, default, default);
// Mark the silo as dead
while (true)
{
var table = await membershipTable.ReadAll();
var row = table.Members.Single(e => e.Item1.SiloAddress.Equals(this.localSilo));
var entry = row.Item1.WithStatus(SiloStatus.Dead);
if (await membershipTable.UpdateRow(entry, row.Item2, table.Version.Next())) break;
}
// Refresh silo status and check that it determines it's dead.
await manager.Refresh();
this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default);
await this.lifecycle.OnStop();
}
/// <summary>
/// Try to suspect another silo of failing but discover that this silo has failed.
/// </summary>
[Fact]
public async Task MembershipTableManager_TrySuspectOrKill_ButIAmKill()
{
var otherSilos = new[]
{
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active),
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
siloLifecycle: this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
await manager.UpdateStatus(SiloStatus.Active);
// Mark the silo as dead
while (true)
{
var table = await membershipTable.ReadAll();
var row = table.Members.Single(e => e.Item1.SiloAddress.Equals(this.localSilo));
var entry = row.Item1.WithStatus(SiloStatus.Dead);
if (await membershipTable.UpdateRow(entry, row.Item2, table.Version.Next())) break;
}
this.fatalErrorHandler.DidNotReceiveWithAnyArgs().OnFatalException(default, default, default);
await manager.TryToSuspectOrKill(otherSilos.First().SiloAddress);
this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default);
}
/// <summary>
/// Try to suspect another silo of failing but discover that it is already dead.
/// </summary>
[Fact]
public async Task MembershipTableManager_TrySuspectOrKill_AlreadyDead()
{
var otherSilos = new[]
{
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:500@100"), SiloStatus.Dead),
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
siloLifecycle: this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
await manager.UpdateStatus(SiloStatus.Active);
var victim = otherSilos.Last().SiloAddress;
await manager.TryToSuspectOrKill(victim);
Assert.Equal(SiloStatus.Dead, manager.MembershipTableSnapshot.GetSiloStatus(victim));
}
/// <summary>
/// Declare a silo dead in a small, 2-silo cluster, requiring one vote ((2 + 1) / 2 = 1).
/// </summary>
[Fact]
public async Task MembershipTableManager_TrySuspectOrKill_DeclareDead_SmallCluster()
{
var otherSilos = new[]
{
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:500@100"), SiloStatus.Dead),
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
siloLifecycle: this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
await manager.UpdateStatus(SiloStatus.Active);
var victim = otherSilos.First().SiloAddress;
await manager.TryToSuspectOrKill(victim);
Assert.Equal(SiloStatus.Dead, manager.MembershipTableSnapshot.GetSiloStatus(victim));
}
/// <summary>
/// Declare a silo dead in a larger cluster, requiring 2 votes (per configuration).
/// </summary>
[Fact]
public async Task MembershipTableManager_TrySuspectOrKill_DeclareDead_LargerCluster()
{
var otherSilos = new[]
{
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:300@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:400@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:500@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:600@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:700@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:800@100"), SiloStatus.Active),
Entry(Silo("127.0.0.1:900@100"), SiloStatus.Dead),
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
siloLifecycle: this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
await manager.UpdateStatus(SiloStatus.Active);
// Try to declare an unknown silo dead
await Assert.ThrowsAsync<KeyNotFoundException>(() => manager.TryToSuspectOrKill(Silo("123.123.123.123:1@1")));
// Multiple votes from the same node should not result in the node being declared dead.
var victim = otherSilos.First().SiloAddress;
await manager.TryToSuspectOrKill(victim);
await manager.TryToSuspectOrKill(victim);
await manager.TryToSuspectOrKill(victim);
Assert.Equal(SiloStatus.Active, manager.MembershipTableSnapshot.GetSiloStatus(victim));
// Manually remove our vote and add another silo's vote so we can be the one to kill the silo.
while (true)
{
var table = await membershipTable.ReadAll();
var row = table.Members.Single(e => e.Item1.SiloAddress.Equals(victim));
var entry = row.Item1.Copy();
entry.SuspectTimes?.Clear();
entry.AddSuspector(otherSilos[2].SiloAddress, DateTime.UtcNow);
if (await membershipTable.UpdateRow(entry, row.Item2, table.Version.Next())) break;
}
await manager.TryToSuspectOrKill(victim);
Assert.Equal(SiloStatus.Dead, manager.MembershipTableSnapshot.GetSiloStatus(victim));
// One down, one to go. Now overshoot votes and kill ourselves instead (due to internal error).
victim = otherSilos[1].SiloAddress;
while (true)
{
var table = await membershipTable.ReadAll();
var row = table.Members.Single(e => e.Item1.SiloAddress.Equals(victim));
var entry = row.Item1.Copy();
entry.SuspectTimes?.Clear();
entry.AddSuspector(otherSilos[2].SiloAddress, DateTime.UtcNow);
entry.AddSuspector(otherSilos[3].SiloAddress, DateTime.UtcNow);
entry.AddSuspector(otherSilos[4].SiloAddress, DateTime.UtcNow);
if (await membershipTable.UpdateRow(entry, row.Item2, table.Version.Next())) break;
}
this.fatalErrorHandler.DidNotReceiveWithAnyArgs().OnFatalException(default, default, default);
await manager.TryToSuspectOrKill(victim);
this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default);
// We killed ourselves and should not have marked the other silo as dead.
await manager.Refresh();
Assert.Equal(SiloStatus.Active, manager.MembershipTableSnapshot.GetSiloStatus(victim));
}
/// <summary>
/// Tests <see cref="MembershipTableManager"/> table refresh behavior.
/// </summary>
[Fact]
public async Task MembershipTableManager_Refresh()
{
var timers = new List<DelegateAsyncTimer>();
var timerCalls = new ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>();
var timerFactory = new DelegateAsyncTimerFactory(
(period, name) =>
{
var t = new DelegateAsyncTimer(
overridePeriod =>
{
var task = new TaskCompletionSource<bool>();
timerCalls.Enqueue((overridePeriod, task));
return task.Task;
});
timers.Add(t);
return t;
});
var otherSilos = new[]
{
Entry(Silo("127.0.0.1:200@100"), SiloStatus.Active)
};
var membershipTable = new InMemoryMembershipTable(new TableVersion(123, "123"), otherSilos);
var manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: timerFactory,
siloLifecycle: this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)manager).Participate(this.lifecycle);
await this.lifecycle.OnStart();
// Test that retries occur after an exception.
(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion) timer = (default, default);
while (!timerCalls.TryDequeue(out timer)) await Task.Delay(1);
var counter = 0;
membershipTable.OnReadAll = () => { if (counter++ == 0) throw new Exception("no"); };
timer.Completion.TrySetResult(true);
this.fatalErrorHandler.DidNotReceiveWithAnyArgs().OnFatalException(default, default, default);
// A shorter delay should be provided after a transient failure.
while (!timerCalls.TryDequeue(out timer)) await Task.Delay(10);
membershipTable.OnReadAll = null;
Assert.True(timer.DelayOverride.HasValue);
timer.Completion.TrySetResult(true);
// The standard delay should be used thereafter.
while (!timerCalls.TryDequeue(out timer)) await Task.Delay(10);
Assert.False(timer.DelayOverride.HasValue);
timer.Completion.TrySetResult(true);
// If for some reason the timer itself fails (or something else), the silo should crash
while (!timerCalls.TryDequeue(out timer)) await Task.Delay(10);
timer.Completion.TrySetException(new Exception("no again"));
this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default);
Assert.False(timerCalls.TryDequeue(out timer));
await this.lifecycle.OnStop();
}
private static SiloAddress Silo(string value) => SiloAddress.FromParsableString(value);
private static MembershipEntry Entry(SiloAddress address, SiloStatus status)
{
return new MembershipEntry { SiloAddress = address, Status = status };
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
namespace Pathfinding {
/** Radius path modifier for offsetting paths.
* \ingroup modifiers
*
* The radius modifier will offset the path to create the effect
* of adjusting it to the characters radius.
* It gives good results on navmeshes which have not been offset with the
* character radius during scan. Especially useful when characters with different
* radiuses are used on the same navmesh. It is also useful when using
* rvo local avoidance with the RVONavmesh since the RVONavmesh assumes the
* navmesh has not been offset with the character radius.
*
* This modifier assumes all paths are in the XZ plane (i.e Y axis is up).
*
* It is recommended to use the Funnel Modifier on the path as well.
*
* \shadowimage{radius_modifier.png}
*
* \see RVONavmesh
* \see modifiers
*
* Also check out the howto page "Using Modifiers".
*
* \astarpro
*
* \since Added in 3.2.6
*/
[AddComponentMenu("Pathfinding/Modifiers/Radius Offset")]
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_radius_modifier.php")]
public class RadiusModifier : MonoModifier {
#if UNITY_EDITOR
[UnityEditor.MenuItem("CONTEXT/Seeker/Add Radius Modifier")]
public static void AddComp (UnityEditor.MenuCommand command) {
(command.context as Component).gameObject.AddComponent(typeof(RadiusModifier));
}
#endif
public override int Order { get { return 41; } }
/** Radius of the circle segments generated.
* Usually similar to the character radius.
*/
public float radius = 1f;
/** Detail of generated circle segments.
* Measured as steps per full circle.
*
* It is more performant to use a low value.
* For movement, using a high value will barely improve path quality.
*/
public float detail = 10;
/** Calculates inner tangents for a pair of circles.
* \param p1 Position of first circle
* \param p2 Position of the second circle
* \param r1 Radius of the first circle
* \param r2 Radius of the second circle
* \param a Angle from the line joining the centers of the circles to the inner tangents.
* \param sigma World angle from p1 to p2 (in XZ space)
*
* Add \a a to \a sigma to get the first tangent angle, subtract \a a from \a sigma to get the second tangent angle.
*
* \returns True on success. False when the circles are overlapping.
*/
bool CalculateCircleInner (Vector3 p1, Vector3 p2, float r1, float r2, out float a, out float sigma) {
float dist = (p1-p2).magnitude;
if (r1+r2 > dist) {
a = 0;
sigma = 0;
return false;
}
a = (float)Math.Acos((r1+r2)/dist);
sigma = (float)Math.Atan2(p2.z-p1.z, p2.x-p1.x);
return true;
}
/** Calculates outer tangents for a pair of circles.
* \param p1 Position of first circle
* \param p2 Position of the second circle
* \param r1 Radius of the first circle
* \param r2 Radius of the second circle
* \param a Angle from the line joining the centers of the circles to the inner tangents.
* \param sigma World angle from p1 to p2 (in XZ space)
*
* Add \a a to \a sigma to get the first tangent angle, subtract \a a from \a sigma to get the second tangent angle.
*
* \returns True on success. False on failure (more specifically when |r1-r2| > |p1-p2| )
*/
bool CalculateCircleOuter (Vector3 p1, Vector3 p2, float r1, float r2, out float a, out float sigma) {
float dist = (p1-p2).magnitude;
if (Math.Abs(r1 - r2) > dist) {
a = 0;
sigma = 0;
return false;
}
a = (float)Math.Acos((r1-r2)/dist);
sigma = (float)Math.Atan2(p2.z-p1.z, p2.x-p1.x);
return true;
}
[System.Flags]
enum TangentType {
OuterRight = 1 << 0,
InnerRightLeft = 1 << 1,
InnerLeftRight = 1 << 2,
OuterLeft = 1 << 3,
Outer = OuterRight | OuterLeft,
Inner = InnerRightLeft | InnerLeftRight
}
TangentType CalculateTangentType (Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) {
bool l1 = VectorMath.RightOrColinearXZ(p1, p2, p3);
bool l2 = VectorMath.RightOrColinearXZ(p2, p3, p4);
return (TangentType)(1 << ((l1 ? 2 : 0) + (l2 ? 1 : 0)));
}
TangentType CalculateTangentTypeSimple (Vector3 p1, Vector3 p2, Vector3 p3) {
bool l2 = VectorMath.RightOrColinearXZ(p1, p2, p3);
bool l1 = l2;
return (TangentType)(1 << ((l1 ? 2 : 0) + (l2 ? 1 : 0)));
}
public override void Apply (Path p) {
List<Vector3> vs = p.vectorPath;
List<Vector3> res = Apply(vs);
if (res != vs) {
Pathfinding.Util.ListPool<Vector3>.Release(ref p.vectorPath);
p.vectorPath = res;
}
}
float[] radi = new float[10];
float[] a1 = new float[10];
float[] a2 = new float[10];
bool[] dir = new bool[10];
/** Apply this modifier on a raw Vector3 list */
public List<Vector3> Apply (List<Vector3> vs) {
if (vs == null || vs.Count < 3) return vs;
/** \todo Do something about these allocations */
if (radi.Length < vs.Count) {
radi = new float[vs.Count];
a1 = new float[vs.Count];
a2 = new float[vs.Count];
dir = new bool[vs.Count];
}
for (int i = 0; i < vs.Count; i++) {
radi[i] = radius;
}
radi[0] = 0;
radi[vs.Count-1] = 0;
int count = 0;
for (int i = 0; i < vs.Count-1; i++) {
count++;
if (count > 2*vs.Count) {
Debug.LogWarning("Could not resolve radiuses, the path is too complex. Try reducing the base radius");
break;
}
TangentType tt;
if (i == 0) {
tt = CalculateTangentTypeSimple(vs[i], vs[i+1], vs[i+2]);
} else if (i == vs.Count-2) {
tt = CalculateTangentTypeSimple(vs[i-1], vs[i], vs[i+1]);
} else {
tt = CalculateTangentType(vs[i-1], vs[i], vs[i+1], vs[i+2]);
}
//DrawCircle (vs[i], radi[i], Color.yellow);
if ((tt & TangentType.Inner) != 0) {
//Angle to tangent
float a;
//Angle to other circle
float sigma;
//Calculate angles to the next circle and angles for the inner tangents
if (!CalculateCircleInner(vs[i], vs[i+1], radi[i], radi[i+1], out a, out sigma)) {
//Failed, try modifying radiuses
float magn = (vs[i+1]-vs[i]).magnitude;
radi[i] = magn*(radi[i]/(radi[i]+radi[i+1]));
radi[i+1] = magn - radi[i];
radi[i] *= 0.99f;
radi[i+1] *= 0.99f;
i -= 2;
continue;
}
if (tt == TangentType.InnerRightLeft) {
a2[i] = sigma-a;
a1[i+1] = sigma-a + (float)Math.PI;
dir[i] = true;
} else {
a2[i] = sigma+a;
a1[i+1] = sigma+a + (float)Math.PI;
dir[i] = false;
}
} else {
float sigma;
float a;
//Calculate angles to the next circle and angles for the outer tangents
if (!CalculateCircleOuter(vs[i], vs[i+1], radi[i], radi[i+1], out a, out sigma)) {
//Failed, try modifying radiuses
if (i == vs.Count-2) {
//The last circle has a fixed radius at 0, don't modify it
radi[i] = (vs[i+1]-vs[i]).magnitude;
radi[i] *= 0.99f;
i -= 1;
} else {
if (radi[i] > radi[i+1]) {
radi[i+1] = radi[i] - (vs[i+1]-vs[i]).magnitude;
} else {
radi[i+1] = radi[i] + (vs[i+1]-vs[i]).magnitude;
}
radi[i+1] *= 0.99f;
}
i -= 1;
continue;
}
if (tt == TangentType.OuterRight) {
a2[i] = sigma-a;
a1[i+1] = sigma-a;
dir[i] = true;
} else {
a2[i] = sigma+a;
a1[i+1] = sigma+a;
dir[i] = false;
}
}
}
List<Vector3> res = Pathfinding.Util.ListPool<Vector3>.Claim();
res.Add(vs[0]);
if (detail < 1) detail = 1;
float step = (float)(2*Math.PI)/detail;
for (int i = 1; i < vs.Count-1; i++) {
float start = a1[i];
float end = a2[i];
float rad = radi[i];
if (dir[i]) {
if (end < start) end += (float)Math.PI*2;
for (float t = start; t < end; t += step) {
res.Add(new Vector3((float)Math.Cos(t), 0, (float)Math.Sin(t))*rad + vs[i]);
}
} else {
if (start < end) start += (float)Math.PI*2;
for (float t = start; t > end; t -= step) {
res.Add(new Vector3((float)Math.Cos(t), 0, (float)Math.Sin(t))*rad + vs[i]);
}
}
}
res.Add(vs[vs.Count-1]);
return res;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: money/rpc/account_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Money.RPC {
public static partial class AccountSvc
{
static readonly string __ServiceName = "holms.types.money.rpc.AccountSvc";
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> __Marshaller_AccountSvcEnumResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Accounting.AccountIndicator> __Marshaller_AccountIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Accounting.AccountIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Accounting.Account> __Marshaller_Account = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Accounting.Account.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse> __Marshaller_AccountSvcCreateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse> __Marshaller_AccountSvcUpdateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse> __Marshaller_AccountSvcDeleteResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq> __Marshaller_AccountSvcAllByCategoryReq = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse>(
grpc::MethodType.Unary,
__ServiceName,
"All",
__Marshaller_Empty,
__Marshaller_AccountSvcEnumResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.Accounting.AccountIndicator, global::HOLMS.Types.Money.Accounting.Account> __Method_GetById = new grpc::Method<global::HOLMS.Types.Money.Accounting.AccountIndicator, global::HOLMS.Types.Money.Accounting.Account>(
grpc::MethodType.Unary,
__ServiceName,
"GetById",
__Marshaller_AccountIndicator,
__Marshaller_Account);
static readonly grpc::Method<global::HOLMS.Types.Money.Accounting.Account, global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse> __Method_Create = new grpc::Method<global::HOLMS.Types.Money.Accounting.Account, global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse>(
grpc::MethodType.Unary,
__ServiceName,
"Create",
__Marshaller_Account,
__Marshaller_AccountSvcCreateResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.Accounting.Account, global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse> __Method_Update = new grpc::Method<global::HOLMS.Types.Money.Accounting.Account, global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse>(
grpc::MethodType.Unary,
__ServiceName,
"Update",
__Marshaller_Account,
__Marshaller_AccountSvcUpdateResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.Accounting.Account, global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse> __Method_Delete = new grpc::Method<global::HOLMS.Types.Money.Accounting.Account, global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse>(
grpc::MethodType.Unary,
__ServiceName,
"Delete",
__Marshaller_Account,
__Marshaller_AccountSvcDeleteResponse);
static readonly grpc::Method<global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq, global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> __Method_AllByCategory = new grpc::Method<global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq, global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AllByCategory",
__Marshaller_AccountSvcAllByCategoryReq,
__Marshaller_AccountSvcEnumResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Money.RPC.AccountSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of AccountSvc</summary>
public abstract partial class AccountSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Accounting.Account> GetById(global::HOLMS.Types.Money.Accounting.AccountIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse> Create(global::HOLMS.Types.Money.Accounting.Account request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse> Update(global::HOLMS.Types.Money.Accounting.Account request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse> Delete(global::HOLMS.Types.Money.Accounting.Account request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> AllByCategory(global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for AccountSvc</summary>
public partial class AccountSvcClient : grpc::ClientBase<AccountSvcClient>
{
/// <summary>Creates a new client for AccountSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public AccountSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for AccountSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public AccountSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected AccountSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected AccountSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return All(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request);
}
public virtual global::HOLMS.Types.Money.Accounting.Account GetById(global::HOLMS.Types.Money.Accounting.AccountIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.Accounting.Account GetById(global::HOLMS.Types.Money.Accounting.AccountIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Accounting.Account> GetByIdAsync(global::HOLMS.Types.Money.Accounting.AccountIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Accounting.Account> GetByIdAsync(global::HOLMS.Types.Money.Accounting.AccountIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request);
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse Create(global::HOLMS.Types.Money.Accounting.Account request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse Create(global::HOLMS.Types.Money.Accounting.Account request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse> CreateAsync(global::HOLMS.Types.Money.Accounting.Account request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcCreateResponse> CreateAsync(global::HOLMS.Types.Money.Accounting.Account request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request);
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse Update(global::HOLMS.Types.Money.Accounting.Account request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse Update(global::HOLMS.Types.Money.Accounting.Account request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse> UpdateAsync(global::HOLMS.Types.Money.Accounting.Account request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcUpdateResponse> UpdateAsync(global::HOLMS.Types.Money.Accounting.Account request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request);
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse Delete(global::HOLMS.Types.Money.Accounting.Account request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse Delete(global::HOLMS.Types.Money.Accounting.Account request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse> DeleteAsync(global::HOLMS.Types.Money.Accounting.Account request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcDeleteResponse> DeleteAsync(global::HOLMS.Types.Money.Accounting.Account request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request);
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse AllByCategory(global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllByCategory(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse AllByCategory(global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AllByCategory, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> AllByCategoryAsync(global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllByCategoryAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.RPC.AccountSvcEnumResponse> AllByCategoryAsync(global::HOLMS.Types.Money.RPC.AccountSvcAllByCategoryReq request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AllByCategory, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override AccountSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new AccountSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(AccountSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_All, serviceImpl.All)
.AddMethod(__Method_GetById, serviceImpl.GetById)
.AddMethod(__Method_Create, serviceImpl.Create)
.AddMethod(__Method_Update, serviceImpl.Update)
.AddMethod(__Method_Delete, serviceImpl.Delete)
.AddMethod(__Method_AllByCategory, serviceImpl.AllByCategory).Build();
}
}
}
#endregion
| |
// Copyright 2021 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Google.Cloud.Spanner.Connection.MockServer;
using Google.Cloud.Spanner.NHibernate.Tests.Entities;
using Google.Cloud.Spanner.V1;
using Google.Protobuf.WellKnownTypes;
using NHibernate;
using Xunit;
using TypeCode = Google.Cloud.Spanner.V1.TypeCode;
namespace Google.Cloud.Spanner.NHibernate.Tests
{
/// <summary>
/// Tests optimistic concurrency using an in-mem Spanner mock server.
/// </summary>
public class NHibernateVersioningMockServerTests : IClassFixture<NHibernateMockServerFixture>
{
private readonly NHibernateMockServerFixture _fixture;
public NHibernateVersioningMockServerTests(NHibernateMockServerFixture service)
{
_fixture = service;
service.SpannerMock.Reset();
}
[Fact]
public async Task VersionNumberIsAutomaticallyGeneratedOnInsertAndUpdate()
{
var insertSql = "INSERT INTO SingerWithVersion (Version, FirstName, LastName, SingerId) VALUES (@p0, @p1, @p2, @p3)";
_fixture.SpannerMock.AddOrUpdateStatementResult(insertSql, StatementResult.CreateUpdateCount(1L));
var singer = new SingerWithVersion { SingerId = 1L, FirstName = "Pete", LastName = "Allison" };
using (var session = _fixture.SessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
await session.SaveAsync(singer);
await transaction.CommitAsync();
}
}
Assert.Collection(
_fixture.SpannerMock.Requests.OfType<ExecuteSqlRequest>(),
request =>
{
Assert.Equal(insertSql, request.Sql);
// Verify that the version is 1.
Assert.Equal(Value.ForString("1"), request.Params.Fields["p0"]);
Assert.Equal(Value.ForString("Pete"), request.Params.Fields["p1"]);
Assert.Equal(Value.ForString("Allison"), request.Params.Fields["p2"]);
Assert.Equal(Value.ForString("1"), request.Params.Fields["p3"]);
}
);
_fixture.SpannerMock.Reset();
// Update the singer and verify that the version number is included in the WHERE clause and is updated.
var updateSql = "UPDATE SingerWithVersion SET Version = @p0, FirstName = @p1, LastName = @p2 WHERE SingerId = @p3 AND Version = @p4";
_fixture.SpannerMock.AddOrUpdateStatementResult(updateSql, StatementResult.CreateUpdateCount(1L));
singer.LastName = "Peterson - Allison";
using (var session = _fixture.SessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
await session.SaveOrUpdateAsync(singer);
await transaction.CommitAsync();
}
}
Assert.Collection(_fixture.SpannerMock.Requests.OfType<ExecuteSqlRequest>(), updateQueryRequest =>
{
Assert.NotNull(updateQueryRequest);
Assert.Equal(updateSql, updateQueryRequest.Sql);
// Verify that the version that is set is 2.
Assert.Equal(Value.ForString("2"), updateQueryRequest.Params.Fields["p0"]);
Assert.Equal(Value.ForString("Pete"), updateQueryRequest.Params.Fields["p1"]);
Assert.Equal(Value.ForString("Peterson - Allison"), updateQueryRequest.Params.Fields["p2"]);
Assert.Equal(Value.ForString("1"), updateQueryRequest.Params.Fields["p3"]);
// Verify that the version that is checked is 1.
Assert.Equal(Value.ForString("1"), updateQueryRequest.Params.Fields["p4"]);
});
}
[Fact]
public async Task UpdateFailsIfVersionNumberChanged()
{
var updateSql = "UPDATE SingerWithVersion SET Version = @p0, FirstName = @p1, LastName = @p2 WHERE SingerId = @p3 AND Version = @p4";
var selectSql = "SELECT singerwith0_.SingerId as singerid1_4_0_, singerwith0_.Version as version2_4_0_, singerwith0_.FirstName as firstname3_4_0_, singerwith0_.LastName as lastname4_4_0_ FROM SingerWithVersion singerwith0_ WHERE singerwith0_.SingerId=@p0";
// Set the update count to 0 to indicate that the row was not found.
_fixture.SpannerMock.AddOrUpdateStatementResult(updateSql, StatementResult.CreateUpdateCount(0L));
_fixture.SpannerMock.AddOrUpdateStatementResult(selectSql, StatementResult.CreateResultSet(new List<Tuple<V1.TypeCode, string>>
{
Tuple.Create(TypeCode.Int64, "singerid1_4_0_"),
Tuple.Create(TypeCode.Int64, "version2_4_0_"),
Tuple.Create(TypeCode.String, "firstname3_4_0_"),
Tuple.Create(TypeCode.String, "lastname4_4_0_")
}, new List<object[]>
{
new object[]{"1", "1", "Pete", "Allison"}
}));
using (var session = _fixture.SessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var singer = await session.LoadAsync<SingerWithVersion>(1L);
singer.LastName = "Allison - Peterson";
await Assert.ThrowsAsync<StaleStateException>(() => session.FlushAsync());
// Update the update count to 1 to simulate a resolved version conflict.
_fixture.SpannerMock.AddOrUpdateStatementResult(updateSql, StatementResult.CreateUpdateCount(1L));
await transaction.CommitAsync();
}
}
}
[CombinatorialData]
[Theory]
public async Task VersionNumberIsAutomaticallyGeneratedOnInsertAndUpdateUsingMutations(bool useAsync)
{
var singer = new SingerWithVersion { SingerId = 50L, FirstName = "Pete", LastName = "Allison" };
using (var session = _fixture.SessionFactoryUsingMutations.OpenSession())
{
using (var transaction = session.BeginTransaction(MutationUsage.Always))
{
if (useAsync)
{
await session.SaveAsync(singer);
await transaction.CommitAsync();
}
else
{
session.Save(singer);
transaction.Commit();
await Task.CompletedTask;
}
}
}
Assert.Empty(_fixture.SpannerMock.Requests.OfType<ExecuteBatchDmlRequest>());
Assert.Collection(
_fixture.SpannerMock.Requests.OfType<CommitRequest>(),
r =>
{
Assert.Collection(
r.Mutations,
mutation =>
{
Assert.Equal(Mutation.OperationOneofCase.Insert, mutation.OperationCase);
Assert.Equal("SingerWithVersion", mutation.Insert.Table);
Assert.Collection(
mutation.Insert.Columns,
column => Assert.Equal("Version", column),
column => Assert.Equal("FirstName", column),
column => Assert.Equal("LastName", column),
column => Assert.Equal("SingerId", column)
);
Assert.Collection(
mutation.Insert.Values,
row => Assert.Collection(
row.Values,
value => Assert.Equal("1", value.StringValue),
value => Assert.Equal("Pete", value.StringValue),
value => Assert.Equal("Allison", value.StringValue),
value => Assert.Equal("50", value.StringValue)
)
);
}
);
});
_fixture.SpannerMock.Reset();
var checkVersionSql = "SELECT 1 AS C FROM SingerWithVersion WHERE SingerId = @p0 AND Version = @p1";
_fixture.SpannerMock.AddOrUpdateStatementResult(checkVersionSql, StatementResult.CreateResultSet(
new []{new Tuple<TypeCode, string>(TypeCode.Int64, "C")},
new []{ new object[] {1L}}));
// Update the singer and verify that a SELECT statement that checks the version number is executed.
singer.LastName = "Peterson - Allison";
using (var session = _fixture.SessionFactoryUsingMutations.OpenSession())
{
using (var transaction = session.BeginTransaction(MutationUsage.Always))
{
await session.SaveOrUpdateAsync(singer);
await transaction.CommitAsync();
}
}
Assert.Empty(_fixture.SpannerMock.Requests.OfType<ExecuteBatchDmlRequest>());
Assert.Collection(_fixture.SpannerMock.Requests.OfType<ExecuteSqlRequest>(),
request =>
{
Assert.Equal(checkVersionSql, request.Sql);
Assert.Collection(request.Params.Fields,
p => Assert.Equal("50", p.Value.StringValue), // SingerId
p => Assert.Equal("1", p.Value.StringValue) // Version
);
});
Assert.Collection(
_fixture.SpannerMock.Requests.OfType<CommitRequest>(),
r =>
{
Assert.Collection(
r.Mutations,
mutation =>
{
Assert.Equal(Mutation.OperationOneofCase.Update, mutation.OperationCase);
Assert.Equal("SingerWithVersion", mutation.Update.Table);
Assert.Collection(
mutation.Update.Columns,
column => Assert.Equal("Version", column),
column => Assert.Equal("FirstName", column),
column => Assert.Equal("LastName", column),
column => Assert.Equal("SingerId", column)
);
Assert.Collection(
mutation.Update.Values,
row => Assert.Collection(
row.Values,
// Verify that the version that is set is 2.
value => Assert.Equal("2", value.StringValue),
value => Assert.Equal("Pete", value.StringValue),
value => Assert.Equal("Peterson - Allison", value.StringValue),
value => Assert.Equal("50", value.StringValue)
)
);
}
);
}
);
}
[CombinatorialData]
[Theory]
public async Task UpdateFailsIfVersionNumberChangedUsingMutations(bool useAsync)
{
var checkVersionSql = "SELECT 1 AS C FROM SingerWithVersion WHERE SingerId = @p0 AND Version = @p1";
// Add an empty result for the version check query.
_fixture.SpannerMock.AddOrUpdateStatementResult(checkVersionSql, StatementResult.CreateResultSet(
new List<Tuple<TypeCode, string>> {Tuple.Create(TypeCode.Int64, "C")}, new List<object[]>()));
var selectSql = "/* load Google.Cloud.Spanner.NHibernate.Tests.Entities.SingerWithVersion */ SELECT singerwith0_.SingerId as singerid1_4_0_, singerwith0_.Version as version2_4_0_, singerwith0_.FirstName as firstname3_4_0_, singerwith0_.LastName as lastname4_4_0_ FROM SingerWithVersion singerwith0_ WHERE singerwith0_.SingerId=@p0";
_fixture.SpannerMock.AddOrUpdateStatementResult(selectSql, StatementResult.CreateResultSet(new List<Tuple<V1.TypeCode, string>>
{
Tuple.Create(TypeCode.Int64, "singerid1_4_0_"),
Tuple.Create(TypeCode.Int64, "version2_4_0_"),
Tuple.Create(TypeCode.String, "firstname3_4_0_"),
Tuple.Create(TypeCode.String, "lastname4_4_0_")
}, new List<object[]>
{
new object[]{"50", "1", "Pete", "Allison"}
}));
using (var session = _fixture.SessionFactoryUsingMutations.OpenSession())
{
using (var transaction = session.BeginTransaction(MutationUsage.Always))
{
if (useAsync)
{
var singer = await session.LoadAsync<SingerWithVersion>(50L);
singer.LastName = "Allison - Peterson";
// This will fail because no result is found by the check version SELECT statement.
await Assert.ThrowsAsync<StaleStateException>(() => transaction.CommitAsync());
}
else
{
var singer = session.Load<SingerWithVersion>(50L);
singer.LastName = "Allison - Peterson";
// This will fail because no result is found by the check version SELECT statement.
Assert.Throws<StaleStateException>(() => transaction.Commit());
}
}
}
// Update the result of the check version SELECT statement to simulate a resolved version conflict.
_fixture.SpannerMock.AddOrUpdateStatementResult(checkVersionSql, StatementResult.CreateResultSet(
new []{new Tuple<TypeCode, string>(TypeCode.Int64, "C")},
new []{ new object[] {1L}}));
using (var session = _fixture.SessionFactoryUsingMutations.OpenSession())
{
using (var transaction = session.BeginTransaction(MutationUsage.Always))
{
if (useAsync)
{
var singer = await session.LoadAsync<SingerWithVersion>(50L);
singer.LastName = "Allison - Peterson";
// This will now succeed because a result is found by the version check.
await transaction.CommitAsync();
}
else
{
var singer = session.Load<SingerWithVersion>(50L);
singer.LastName = "Allison - Peterson";
// This will now succeed because a result is found by the version check.
transaction.Commit();
await Task.CompletedTask;
}
}
}
// There are two transaction attempts that execute the same SELECT statements.
var requests = _fixture.SpannerMock.Requests.OfType<ExecuteSqlRequest>();
Assert.Collection(requests,
request => Assert.Equal(request.Sql, selectSql),
request =>
{
Assert.Equal(request.Sql, checkVersionSql);
Assert.Collection(request.Params.Fields,
p => Assert.Equal("50", p.Value.StringValue),
p => Assert.Equal("1", p.Value.StringValue)
);
},
request => Assert.Equal(request.Sql, selectSql),
request =>
{
Assert.Equal(request.Sql, checkVersionSql);
Assert.Collection(request.Params.Fields,
p => Assert.Equal("50", p.Value.StringValue),
p => Assert.Equal("1", p.Value.StringValue)
);
}
);
// Only one of the two transactions will commit successfully.
var commitRequests = _fixture.SpannerMock.Requests.OfType<CommitRequest>();
Assert.Collection(commitRequests, commit =>
{
Assert.Collection(commit.Mutations, mutation =>
{
Assert.Equal(Mutation.OperationOneofCase.Update, mutation.OperationCase);
Assert.Equal("SingerWithVersion", mutation.Update.Table);
Assert.Collection(mutation.Update.Columns,
c => Assert.Equal("Version", c),
c => Assert.Equal("LastName", c),
c => Assert.Equal("SingerId", c)
);
Assert.Collection(mutation.Update.Values, row => Assert.Collection(row.Values,
c => Assert.Equal("2", c.StringValue),
c => Assert.Equal("Allison - Peterson", c.StringValue),
c => Assert.Equal("50", c.StringValue)
));
});
});
}
[CombinatorialData]
[Theory]
public async Task DeleteFailsIfVersionNumberChangedUsingMutations(bool useAsync)
{
var checkVersionSql = "SELECT 1 AS C FROM SingerWithVersion WHERE SingerId = @p0 AND Version = @p1";
// Add an empty result for the version check query.
_fixture.SpannerMock.AddOrUpdateStatementResult(checkVersionSql, StatementResult.CreateResultSet(
new List<Tuple<TypeCode, string>> {Tuple.Create(TypeCode.Int64, "C")}, new List<object[]>()));
var selectSql = "/* load Google.Cloud.Spanner.NHibernate.Tests.Entities.SingerWithVersion */ SELECT singerwith0_.SingerId as singerid1_4_0_, singerwith0_.Version as version2_4_0_, singerwith0_.FirstName as firstname3_4_0_, singerwith0_.LastName as lastname4_4_0_ FROM SingerWithVersion singerwith0_ WHERE singerwith0_.SingerId=@p0";
_fixture.SpannerMock.AddOrUpdateStatementResult(selectSql, StatementResult.CreateResultSet(new List<Tuple<V1.TypeCode, string>>
{
Tuple.Create(TypeCode.Int64, "singerid1_4_0_"),
Tuple.Create(TypeCode.Int64, "version2_4_0_"),
Tuple.Create(TypeCode.String, "firstname3_4_0_"),
Tuple.Create(TypeCode.String, "lastname4_4_0_")
}, new List<object[]>
{
new object[]{"50", "1", "Pete", "Allison"}
}));
using (var session = _fixture.SessionFactoryUsingMutations.OpenSession())
{
using (var transaction = session.BeginTransaction(MutationUsage.Always))
{
if (useAsync)
{
var singer = await session.LoadAsync<SingerWithVersion>(50L);
await session.DeleteAsync(singer);
// This will fail because no result is found by the check version SELECT statement.
await Assert.ThrowsAsync<StaleStateException>(() => transaction.CommitAsync());
}
else
{
var singer = session.Load<SingerWithVersion>(50L);
session.Delete(singer);
// This will fail because no result is found by the check version SELECT statement.
Assert.Throws<StaleStateException>(() => transaction.Commit());
await Task.CompletedTask;
}
}
}
// Update the result of the check version SELECT statement to simulate a resolved version conflict.
_fixture.SpannerMock.AddOrUpdateStatementResult(checkVersionSql, StatementResult.CreateResultSet(
new []{new Tuple<TypeCode, string>(TypeCode.Int64, "C")},
new []{ new object[] {1L}}));
using (var session = _fixture.SessionFactoryUsingMutations.OpenSession())
{
using (var transaction = session.BeginTransaction(MutationUsage.Always))
{
if (useAsync)
{
var singer = await session.LoadAsync<SingerWithVersion>(50L);
await session.DeleteAsync(singer);
// This will now succeed because a result is found by the version check.
await transaction.CommitAsync();
}
else
{
var singer = session.Load<SingerWithVersion>(50L);
session.Delete(singer);
// This will now succeed because a result is found by the version check.
transaction.Commit();
}
}
}
// There are two transaction attempts that execute the same SELECT statements.
var requests = _fixture.SpannerMock.Requests.OfType<ExecuteSqlRequest>();
Assert.Collection(requests,
request => Assert.Equal(request.Sql, selectSql),
request =>
{
Assert.Equal(request.Sql, checkVersionSql);
Assert.Collection(request.Params.Fields,
p => Assert.Equal("50", p.Value.StringValue),
p => Assert.Equal("1", p.Value.StringValue)
);
},
request => Assert.Equal(request.Sql, selectSql),
request =>
{
Assert.Equal(request.Sql, checkVersionSql);
Assert.Collection(request.Params.Fields,
p => Assert.Equal("50", p.Value.StringValue),
p => Assert.Equal("1", p.Value.StringValue)
);
}
);
// Only one of the two transactions will commit successfully.
var commitRequests = _fixture.SpannerMock.Requests.OfType<CommitRequest>();
Assert.Collection(commitRequests, commit =>
{
Assert.Collection(commit.Mutations, mutation =>
{
Assert.Equal(Mutation.OperationOneofCase.Delete, mutation.OperationCase);
Assert.Equal("SingerWithVersion", mutation.Delete.Table);
Assert.Collection(mutation.Delete.KeySet.Keys, key => Assert.Collection(key.Values,
c => Assert.Equal("50", c.StringValue)
));
});
});
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// AsnEncodedData.cs
//
namespace System.Security.Cryptography {
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
public class AsnEncodedData {
internal Oid m_oid = null;
internal byte[] m_rawData = null;
internal AsnEncodedData (Oid oid) {
m_oid = oid;
}
internal AsnEncodedData (string oid, CAPI.CRYPTOAPI_BLOB encodedBlob) : this(oid, CAPI.BlobToByteArray(encodedBlob)) {}
internal AsnEncodedData (Oid oid, CAPI.CRYPTOAPI_BLOB encodedBlob) : this(oid, CAPI.BlobToByteArray(encodedBlob)) {}
protected AsnEncodedData () {}
public AsnEncodedData (byte[] rawData) {
Reset(null, rawData);
}
public AsnEncodedData (string oid, byte[] rawData) {
Reset(new Oid(oid), rawData);
}
public AsnEncodedData (Oid oid, byte[] rawData) {
Reset(oid, rawData);
}
public AsnEncodedData (AsnEncodedData asnEncodedData) {
if (asnEncodedData == null)
throw new ArgumentNullException("asnEncodedData");
Reset(asnEncodedData.m_oid, asnEncodedData.m_rawData);
}
public Oid Oid {
get {
return m_oid;
}
set {
if (value == null)
m_oid = null;
else
m_oid = new Oid(value);
}
}
public byte[] RawData {
get {
return m_rawData;
}
set {
if (value == null)
throw new ArgumentNullException("value");
m_rawData = (byte[]) value.Clone();
}
}
public virtual void CopyFrom (AsnEncodedData asnEncodedData) {
if (asnEncodedData == null)
throw new ArgumentNullException("asnEncodedData");
Reset(asnEncodedData.m_oid, asnEncodedData.m_rawData);
}
public virtual string Format (bool multiLine) {
// Return empty string if no data to format.
if (m_rawData == null || m_rawData.Length == 0)
return String.Empty;
// If OID is not present, then we can force CryptFormatObject
// to use hex formatting by providing an empty OID string.
string oidValue = String.Empty;
if (m_oid != null && m_oid.Value != null)
oidValue = m_oid.Value;
return CAPI.CryptFormatObject(CAPI.X509_ASN_ENCODING,
multiLine ? CAPI.CRYPT_FORMAT_STR_MULTI_LINE : 0,
oidValue,
m_rawData);
}
private void Reset (Oid oid, byte[] rawData) {
this.Oid = oid;
this.RawData = rawData;
}
}
public sealed class AsnEncodedDataCollection : ICollection {
private ArrayList m_list = null;
private Oid m_oid = null;
public AsnEncodedDataCollection () {
m_list = new ArrayList();
m_oid = null;
}
public AsnEncodedDataCollection(AsnEncodedData asnEncodedData) : this() {
m_list.Add(asnEncodedData);
}
public int Add (AsnEncodedData asnEncodedData) {
if (asnEncodedData == null)
throw new ArgumentNullException("asnEncodedData");
//
// If m_oid is not null, then OIDs must match.
//
if (m_oid != null) {
string szOid1 = m_oid.Value;
string szOid2 = asnEncodedData.Oid.Value;
if (szOid1 != null && szOid2 != null) {
// Both are not null, so make sure OIDs match.
if (String.Compare(szOid1, szOid2, StringComparison.OrdinalIgnoreCase) != 0)
throw new CryptographicException(SR.GetString(SR.Cryptography_Asn_MismatchedOidInCollection));
}
else if (szOid1 != null || szOid2 != null) {
// Can't be matching, since only one of them is null.
throw new CryptographicException(SR.GetString(SR.Cryptography_Asn_MismatchedOidInCollection));
}
}
return m_list.Add(asnEncodedData);
}
public void Remove (AsnEncodedData asnEncodedData) {
if (asnEncodedData == null)
throw new ArgumentNullException("asnEncodedData");
m_list.Remove(asnEncodedData);
}
public AsnEncodedData this[int index] {
get {
return (AsnEncodedData) m_list[index];
}
}
public int Count {
get {
return m_list.Count;
}
}
public AsnEncodedDataEnumerator GetEnumerator() {
return new AsnEncodedDataEnumerator(this);
}
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator() {
return new AsnEncodedDataEnumerator(this);
}
/// <internalonly/>
void ICollection.CopyTo(Array array, int index) {
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(SR.GetString(SR.Arg_RankMultiDimNotSupported));
if (index < 0 || index >= array.Length)
throw new ArgumentOutOfRangeException("index", SR.GetString(SR.ArgumentOutOfRange_Index));
if (index + this.Count > array.Length)
throw new ArgumentException(SR.GetString(SR.Argument_InvalidOffLen));
for (int i=0; i < this.Count; i++) {
array.SetValue(this[i], index);
index++;
}
}
public void CopyTo(AsnEncodedData[] array, int index) {
((ICollection)this).CopyTo(array, index);
}
public bool IsSynchronized {
get {
return false;
}
}
public Object SyncRoot {
get {
return this;
}
}
}
public sealed class AsnEncodedDataEnumerator : IEnumerator {
private AsnEncodedDataCollection m_asnEncodedDatas;
private int m_current;
private AsnEncodedDataEnumerator() {}
internal AsnEncodedDataEnumerator(AsnEncodedDataCollection asnEncodedDatas) {
m_asnEncodedDatas = asnEncodedDatas;
m_current = -1;
}
public AsnEncodedData Current {
get {
return m_asnEncodedDatas[m_current];
}
}
/// <internalonly/>
Object IEnumerator.Current {
get {
return (Object) m_asnEncodedDatas[m_current];
}
}
public bool MoveNext() {
if (m_current == ((int) m_asnEncodedDatas.Count - 1))
return false;
m_current++;
return true;
}
public void Reset() {
m_current = -1;
}
}
}
| |
namespace Rhino.Commons.Logging
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using log4net.Util;
///<summary>
/// Writes to the database using SqlBulkCopy in async manner.
/// This appender ensures that even if the database is down or takes a long time to respond
/// the application is not being affected.
/// This include avoid trains in the thread pool, which would kill scalaiblity.
///</summary>
/// <example>
/// An example of a SQL Server table that could be logged to:
/// <code lang="SQL">
/// CREATE TABLE [dbo].[Log] (
/// [ID] [int] IDENTITY (1, 1) NOT NULL ,
/// [Date] [datetime] NOT NULL ,
/// [Thread] [varchar] (255) NOT NULL ,
/// [Level] [varchar] (20) NOT NULL ,
/// [Logger] [varchar] (255) NOT NULL ,
/// [Message] [varchar] (4000) NOT NULL
/// ) ON [PRIMARY]
/// </code>
/// </example>
/// <example>
/// An example configuration to log to the above table.
/// IMPORTANT: Column names are Case Sensitive!
/// <code lang="XML" escaped="true">
///<appender name="BulkInsertLogger"
/// type="Rhino.Commons.Logging.AsyncBulkInsertAppender, Rhino.Commons">
/// <bufferSize value="1000" />
/// <tableName value="Logs"/>
/// <connectionStringName value="Logging"/>
///
/// <filter type="log4net.Filter.LoggerMatchFilter">
/// <loggerToMatch value="NHiberante.SQL" />
/// <acceptOnMatch value="false" />
/// </filter>
/// <filter type="log4net.Filter.LoggerMatchFilter">
/// <loggerToMatch value="Rhino.Commons.HttpModules.PagePerformanceModule" />
/// <acceptOnMatch value="false" />
/// </filter>
/// <filter type="log4net.Filter.LevelRangeFilter">
/// <LevelMax value="WARN" />
/// <LevelMin value="INFO" />
/// <acceptOnMatch value="true" />
/// </filter>
///
/// <mapping>
/// <column value="Date" />
/// <layout type="log4net.Layout.RawTimeStampLayout" />
/// </mapping>
/// <mapping>
/// <column value="Thread" />
/// <layout type="log4net.Layout.PatternLayout">
/// <conversionPattern value="%thread" />
/// </layout>
/// </mapping>
/// <mapping>
/// <column value="Level" />
/// <layout type="log4net.Layout.PatternLayout">
/// <conversionPattern value="%level" />
/// </layout>
/// </mapping>
/// <mapping>
/// <column value="Logger" />
/// <layout type="log4net.Layout.PatternLayout">
/// <conversionPattern value="%logger" />
/// </layout>
/// </mapping>
/// <mapping>
/// <column value="Message" />
/// <layout type="log4net.Layout.PatternLayout">
/// <conversionPattern value="%message" />
/// </layout>
/// </mapping>
/// <mapping>
/// <column value="Exception" />
/// <layout type="log4net.Layout.ExceptionLayout" />
/// </mapping>
///
///</appender>
/// </code>
/// </example>
public class AsyncBulkInsertAppender : BufferingAppenderSkeleton
{
private string connectionStringName;
private string connectionString;
readonly List<BulkInsertMapping> mappings = new List<BulkInsertMapping>();
private string tableName;
private SqlBulkCopyOptions options = SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.UseInternalTransaction;
// we want to avoid taking up all the threads in the pool
// if we take undue amount to write to the DB.
// we use the following three variables to write to the DB in this
// way.
readonly object syncLock = new object();
readonly LinkedList<LoggingEvent[]> eventsList = new LinkedList<LoggingEvent[]>();
private bool anotherThreadAlreadyHandlesLogging = false;
public AsyncBulkInsertAppender()
{
Fix = FixFlags.All & ~FixFlags.LocationInfo;
}
public SqlBulkCopyOptions Options
{
get { return options; }
set { options = value; }
}
public string TableName
{
get { return tableName; }
set { tableName = value; }
}
public override void ActivateOptions()
{
foreach (BulkInsertMapping mapping in mappings)
{
mapping.Validate();
}
base.ActivateOptions();
}
/// <summary>
/// Gets or sets the name of the connection string.
/// </summary>
/// <value>The name of the connection string.</value>
public string ConnectionStringName
{
get { return connectionStringName; }
set
{
ConnectionStringSettings con = ConfigurationManager.ConnectionStrings[value];
if (con == null)
throw new ConfigurationErrorsException("Could not find connections string named '" + value + "'");
connectionString = con.ConnectionString;
connectionStringName = value;
}
}
protected override void SendBuffer(LoggingEvent[] events)
{
// we accept some additional complexity here
// in favor of better concurrency. We don't want to
// block all threads in the pool if we have an issue with
// the database. Therefor, we perform thread sync to ensure
// that only a single thread will write to the DB at any given point
ThreadPool.QueueUserWorkItem(delegate
{
lock (syncLock)
{
eventsList.AddLast(events);
if (anotherThreadAlreadyHandlesLogging)
return;
anotherThreadAlreadyHandlesLogging = true;
}
while (true)
{
LoggingEvent[] current;
lock (syncLock)
{
if(eventsList.Count == 0)
{
anotherThreadAlreadyHandlesLogging = false;
return;
}
current = eventsList.First.Value;
eventsList.RemoveFirst();
}
PerformWriteToDatabase(current);
}
});
}
private void PerformWriteToDatabase(IEnumerable<LoggingEvent> events)
{
try
{
DataTable table = CreateTable(events);
using (SqlBulkCopy bulk = new SqlBulkCopy(connectionString, options))
{
foreach (BulkInsertMapping mapping in mappings)
{
bulk.ColumnMappings.Add(mapping.Column, mapping.Column);
}
bulk.DestinationTableName = tableName;
bulk.WriteToServer(table);
}
}
catch (Exception ex)
{
LogLog.Error("Could not write logs to database in the background", ex);
}
}
private DataTable CreateTable(IEnumerable<LoggingEvent> events)
{
DataTable table = new DataTable();
BuildTableSchema(table);
foreach (LoggingEvent le in events)
{
DataRow row = table.NewRow();
foreach (BulkInsertMapping mapping in mappings)
{
mapping.AddValue(le, row);
}
table.Rows.Add(row);
}
return table;
}
private void BuildTableSchema(DataTable table)
{
foreach (BulkInsertMapping mapping in mappings)
{
table.Columns.Add(mapping.Column);
}
}
public void AddMapping(BulkInsertMapping mapping)
{
mappings.Add(mapping);
}
public class BulkInsertMapping
{
private string column;
private IRawLayout layout;
public IRawLayout Layout
{
get { return layout; }
set { layout = value; }
}
public string Column
{
get { return column; }
set { column = value; }
}
public void Validate()
{
if (string.IsNullOrEmpty(Column))
throw new InvalidOperationException("Must specify column name");
if (Layout == null)
throw new InvalidOperationException("Must specify layout");
}
public void AddValue(LoggingEvent loggingEvent, DataRow row)
{
row[Column] = layout.Format(loggingEvent);
}
}
}
}
| |
// 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,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.PythonTools.Infrastructure;
namespace Microsoft.PythonTools.Debugger {
static class Extensions {
/// <summary>
/// Reads a string from the socket which is encoded as:
/// U, byte count, bytes
/// A, byte count, ASCII
///
/// Which supports either UTF-8 or ASCII strings.
/// </summary>
internal static string ReadString(this Stream stream) {
int type = stream.ReadByte();
if (type < 0) {
Debug.Assert(false, "Socket.ReadString failed to read string type");
throw new IOException();
}
bool isUnicode;
switch ((char)type) {
case 'N': // null string
return null;
case 'U':
isUnicode = true;
break;
case 'A':
isUnicode = false;
break;
default:
Debug.Assert(false, "Socket.ReadString failed to parse unknown string type " + (char)type);
throw new IOException();
}
int len = stream.ReadInt32();
byte[] buffer = new byte[len];
stream.ReadToFill(buffer);
if (isUnicode) {
return Encoding.UTF8.GetString(buffer);
} else {
char[] chars = new char[buffer.Length];
for (int i = 0; i < buffer.Length; i++) {
chars[i] = (char)buffer[i];
}
return new string(chars);
}
}
internal static int ReadInt32(this Stream stream) {
return (int)stream.ReadInt64();
}
internal static long ReadInt64(this Stream stream) {
byte[] buf = new byte[8];
stream.ReadToFill(buf);
// Can't use BitConverter because we need to convert big-endian to little-endian here,
// and BitConverter.IsLittleEndian is platform-dependent (and usually true).
ulong hi = (ulong)(uint)((buf[0] << 0x18) | (buf[1] << 0x10) | (buf[2] << 0x08) | (buf[3] << 0x00));
ulong lo = (ulong)(uint)((buf[4] << 0x18) | (buf[5] << 0x10) | (buf[6] << 0x08) | (buf[7] << 0x00));
return (long)((hi << 0x20) | lo);
}
internal static string ReadAsciiString(this Stream stream, int length) {
var buf = new byte[length];
stream.ReadToFill(buf);
return Encoding.ASCII.GetString(buf, 0, buf.Length);
}
internal static void ReadToFill(this Stream stream, byte[] b) {
int count = stream.ReadBytes(b, b.Length);
if (count != b.Length) {
throw new EndOfStreamException();
}
}
internal static int ReadBytes(this Stream stream, byte[] b, int count) {
int i = 0;
while (i < count) {
int read = stream.Read(b, i, count - i);
if (read == 0) {
break;
}
i += read;
}
return i;
}
internal static void WriteInt32(this Stream stream, int x) {
stream.WriteInt64(x);
}
internal static void WriteInt64(this Stream stream, long x) {
// Can't use BitConverter because we need to convert big-endian to little-endian here,
// and BitConverter.IsLittleEndian is platform-dependent (and usually true).
uint hi = (uint)((ulong)x >> 0x20);
uint lo = (uint)((ulong)x & 0xFFFFFFFFu);
byte[] buf = {
(byte)((hi >> 0x18) & 0xFFu),
(byte)((hi >> 0x10) & 0xFFu),
(byte)((hi >> 0x08) & 0xFFu),
(byte)((hi >> 0x00) & 0xFFu),
(byte)((lo >> 0x18) & 0xFFu),
(byte)((lo >> 0x10) & 0xFFu),
(byte)((lo >> 0x08) & 0xFFu),
(byte)((lo >> 0x00) & 0xFFu)
};
stream.Write(buf, 0, buf.Length);
}
internal static void WriteString(this Stream stream, string str) {
byte[] bytes = Encoding.UTF8.GetBytes(str);
stream.WriteInt32(bytes.Length);
if (bytes.Length > 0) {
stream.Write(bytes);
}
}
internal static void Write(this Stream stream, byte[] b) {
stream.Write(b, 0, b.Length);
}
/// <summary>
/// Replaces \uxxxx with the actual unicode char for a prettier display in local variables.
/// </summary>
public static string FixupEscapedUnicodeChars(this string text) {
StringBuilder buf = null;
int i = 0;
int l = text.Length;
int val;
while (i < l) {
char ch = text[i++];
if (ch == '\\') {
if (buf == null) {
buf = new StringBuilder(text.Length);
buf.Append(text, 0, i - 1);
}
if (i >= l) {
return text;
}
ch = text[i++];
if (ch == 'u' || ch == 'U') {
int len = (ch == 'u') ? 4 : 8;
int max = 16;
if (TryParseInt(text, i, len, max, out val)) {
buf.Append((char)val);
i += len;
} else {
return text;
}
} else {
buf.Append("\\");
buf.Append(ch);
}
} else if (buf != null) {
buf.Append(ch);
}
}
if (buf != null) {
return buf.ToString();
}
return text;
}
private static bool TryParseInt(string text, int start, int length, int b, out int value) {
value = 0;
if (start + length > text.Length) {
return false;
}
for (int i = start, end = start + length; i < end; i++) {
int onechar;
if (HexValue(text[i], out onechar) && onechar < b) {
value = value * b + onechar;
} else {
return false;
}
}
return true;
}
private static int HexValue(char ch) {
int value;
if (!HexValue(ch, out value)) {
throw new ArgumentException(Strings.InvalidHexValue.FormatUI(ch), nameof(ch));
}
return value;
}
private static bool HexValue(char ch, out int value) {
switch (ch) {
case '0':
case '\x660': value = 0; break;
case '1':
case '\x661': value = 1; break;
case '2':
case '\x662': value = 2; break;
case '3':
case '\x663': value = 3; break;
case '4':
case '\x664': value = 4; break;
case '5':
case '\x665': value = 5; break;
case '6':
case '\x666': value = 6; break;
case '7':
case '\x667': value = 7; break;
case '8':
case '\x668': value = 8; break;
case '9':
case '\x669': value = 9; break;
default:
if (ch >= 'a' && ch <= 'z') {
value = ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'Z') {
value = ch - 'A' + 10;
} else {
value = -1;
return false;
}
break;
}
return true;
}
}
}
| |
//
// Copyright (c) Microsoft. 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 Microsoft.Azure.Management.SiteRecovery.Models;
using Microsoft.Azure.Management.SiteRecovery;
using Microsoft.Azure.Test;
using System.Linq;
using System.Net;
using Xunit;
using System;
using Microsoft.Azure;
namespace SiteRecovery.Tests
{
public class FailoverTests : SiteRecoveryTestsBase
{
public void E2EFailover()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string fabricId = "6adf9420-b02f-4377-8ab7-ff384e6d792f";
string containerId = "4f94127d-2eb3-449d-a708-250752e93cb4";
var pgs = client.ReplicationProtectedItem.List(fabricId, containerId, RequestHeaders);
PlannedFailoverInputProperties pfoProp = new PlannedFailoverInputProperties()
{
FailoverDirection = "PrimaryToRecovery",
//ProviderConfigurationSettings = new ProviderSpecificFailoverInput()
};
PlannedFailoverInput pfoInput = new PlannedFailoverInput()
{
Properties = pfoProp
};
var failoverExecution = client.ReplicationProtectedItem.PlannedFailover(fabricId, containerId, pgs.ReplicationProtectedItems[0].Name, pfoInput, RequestHeaders);
}
}
public void CommitFailover()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string fabricId = "6adf9420-b02f-4377-8ab7-ff384e6d792f";
string containerId = "4f94127d-2eb3-449d-a708-250752e93cb4";
var pgs = client.ReplicationProtectedItem.List(fabricId, containerId, RequestHeaders);
var commitResp = client.ReplicationProtectedItem.CommitFailover(fabricId, containerId, pgs.ReplicationProtectedItems[0].Name, RequestHeaders);
}
}
public void RR()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string fabricId = "6adf9420-b02f-4377-8ab7-ff384e6d792f";
string containerId = "4f94127d-2eb3-449d-a708-250752e93cb4";
var pgs = client.ReplicationProtectedItem.List(fabricId, containerId, RequestHeaders);
var commitResp = client.ReplicationProtectedItem.Reprotect(fabricId, containerId, pgs.ReplicationProtectedItems[0].Name, new ReverseReplicationInput(), RequestHeaders);
}
}
public void E2ETFO()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string fabricId = "6adf9420-b02f-4377-8ab7-ff384e6d792f";
string containerId = "4f94127d-2eb3-449d-a708-250752e93cb4";
var pgs = client.ReplicationProtectedItem.List(fabricId, containerId, RequestHeaders);
TestFailoverInputProperties tfoProp = new TestFailoverInputProperties()
{
FailoverDirection = "RecoveryToPrimary",
ProviderSpecificDetails = new ProviderSpecificFailoverInput()
};
TestFailoverInput tfoInput = new TestFailoverInput()
{
Properties = tfoProp
};
DateTime startTfoTime = DateTime.UtcNow;
var tfoResp = client.ReplicationProtectedItem.TestFailover(fabricId, containerId, pgs.ReplicationProtectedItems[0].Name, tfoInput, RequestHeaders);
Job tfoJob = MonitoringHelper.GetJobId(
MonitoringHelper.TestFailoverJobName,
startTfoTime,
client,
RequestHeaders);
ResumeJobParamsProperties resJobProp = new ResumeJobParamsProperties()
{
Comments = "ResumeTfo"
};
ResumeJobParams resumeJobParams = new ResumeJobParams()
{
Properties = resJobProp
};
var resumeJob = client.Jobs.Resume(tfoJob.Name, resumeJobParams, RequestHeaders);
}
}
public void E2EUFO()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string fabricId = "6adf9420-b02f-4377-8ab7-ff384e6d792f";
string containerId = "4f94127d-2eb3-449d-a708-250752e93cb4";
var pgs = client.ReplicationProtectedItem.List(fabricId, containerId, RequestHeaders);
UnplannedFailoverInputProperties ufoProp = new UnplannedFailoverInputProperties()
{
FailoverDirection = "RecoveryToPrimary",
SourceSiteOperations = "NotRequired",
ProviderSpecificDetails = new ProviderSpecificFailoverInput()
};
UnplannedFailoverInput ufoInput = new UnplannedFailoverInput()
{
Properties = ufoProp
};
var ufoResp = client.ReplicationProtectedItem.UnplannedFailover(fabricId, containerId, pgs.ReplicationProtectedItems[0].Name, ufoInput, RequestHeaders);
}
}
public void ApplyRecoveryPoint()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
var fabrics = client.Fabrics.List(RequestHeaders);
Fabric selectedFabric = null;
ProtectionContainer selectedContainer = null;
foreach (var fabric in fabrics.Fabrics)
{
if (fabric.Properties.CustomDetails.InstanceType.Contains("VMM"))
{
selectedFabric = fabric;
break;
}
}
var containers = client.ProtectionContainer.List(selectedFabric.Name, RequestHeaders);
foreach (var container in containers.ProtectionContainers)
{
if (container.Properties.ProtectedItemCount > 0
&& container.Properties.Role.Equals("Primary"))
{
selectedContainer = container;
break;
}
}
string fabricId = selectedFabric.Name;
string containerId = selectedContainer.Name;
if (selectedContainer != null)
{
var pgs = client.ReplicationProtectedItem.List(fabricId, containerId, RequestHeaders);
var rps = client.RecoveryPoint.List(fabricId, containerId, pgs.ReplicationProtectedItems[0].Name, RequestHeaders);
ApplyRecoveryPointInputProperties applyRpProp = new ApplyRecoveryPointInputProperties()
{
RecoveryPointId = rps.RecoveryPoints[rps.RecoveryPoints.Count - 2].Id,
ProviderSpecificDetails = new HyperVReplicaAzureApplyRecoveryPointInput()
{
VaultLocation = "SoutheastAsia"
}
};
ApplyRecoveryPointInput applyRpInput = new ApplyRecoveryPointInput()
{
Properties = applyRpProp
};
var applyRpResp = client.ReplicationProtectedItem.ApplyRecoveryPoint(
fabricId,
containerId,
pgs.ReplicationProtectedItems[0].Name,
applyRpInput,
RequestHeaders);
}
else
{
throw new System.Exception("Container not found.");
}
}
}
public void InMageAzureV2UnplannedFailover()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string vmId = "7192c867-b38e-11e5-af2b-0050569e66ab";
var responseServers = client.Fabrics.List(RequestHeaders);
Assert.True(
responseServers.Fabrics.Count > 0,
"Servers count can't be less than 1");
var vmWareFabric = responseServers.Fabrics.First(
fabric => fabric.Properties.CustomDetails.InstanceType == "VMware");
Assert.NotNull(vmWareFabric);
var containersResponse = client.ProtectionContainer.List(
vmWareFabric.Name,
RequestHeaders);
Assert.NotNull(containersResponse);
Assert.True(
containersResponse.ProtectionContainers.Count > 0,
"Containers count can't be less than 1.");
var protectedItemsResponse = client.ReplicationProtectedItem.Get(
vmWareFabric.Name,
containersResponse.ProtectionContainers[0].Name,
vmId + "-Protected",
RequestHeaders);
Assert.NotNull(protectedItemsResponse);
Assert.NotNull(protectedItemsResponse.ReplicationProtectedItem);
var protectedItem = protectedItemsResponse.ReplicationProtectedItem;
Assert.NotNull(protectedItem.Properties.ProviderSpecificDetails);
var vmWareAzureV2Details = protectedItem.Properties.ProviderSpecificDetails
as InMageAzureV2ProviderSpecificSettings;
Assert.NotNull(vmWareAzureV2Details);
UnplannedFailoverInput ufoInput = new UnplannedFailoverInput()
{
Properties = new UnplannedFailoverInputProperties()
{
FailoverDirection = "PrimaryToRecovery",
ProviderSpecificDetails = new InMageAzureV2FailoverProviderInput
{
RecoveryPointId = "",
VaultLocation = "West US"
},
SourceSiteOperations = "Required"
}
};
var failoverExecution = client.ReplicationProtectedItem.UnplannedFailover(
vmWareFabric.Name,
containersResponse.ProtectionContainers[0].Name,
protectedItem.Name,
ufoInput,
RequestHeaders);
Assert.NotNull(failoverExecution);
Assert.Equal(OperationStatus.Succeeded, failoverExecution.Status);
}
}
public void InMageUnplannedFailover()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string vmId = "7192c867-b38e-11e5-af2b-0050569e66ab";
var responseServers = client.Fabrics.List(RequestHeaders);
Assert.True(
responseServers.Fabrics.Count > 0,
"Servers count can't be less than 1");
var vmWareFabric = responseServers.Fabrics.First(
fabric => fabric.Properties.CustomDetails.InstanceType == "VMware");
Assert.NotNull(vmWareFabric);
var containersResponse = client.ProtectionContainer.List(
vmWareFabric.Name,
RequestHeaders);
Assert.NotNull(containersResponse);
Assert.True(
containersResponse.ProtectionContainers.Count > 0,
"Containers count can't be less than 1.");
var protectedItemsResponse = client.ReplicationProtectedItem.Get(
vmWareFabric.Name,
containersResponse.ProtectionContainers[0].Name,
vmId + "-Protected",
RequestHeaders);
Assert.NotNull(protectedItemsResponse);
Assert.NotNull(protectedItemsResponse.ReplicationProtectedItem);
var protectedItem = protectedItemsResponse.ReplicationProtectedItem;
Assert.NotNull(protectedItem.Properties.ProviderSpecificDetails);
var inMageDetails = protectedItem.Properties.ProviderSpecificDetails
as InMageProviderSpecificSettings;
Assert.NotNull(inMageDetails);
UnplannedFailoverInput ufoInput = new UnplannedFailoverInput()
{
Properties = new UnplannedFailoverInputProperties()
{
FailoverDirection = "PrimaryToRecovery",
ProviderSpecificDetails = new InMageFailoverProviderInput
{
RecoveryPointId = null,
RecoveryPointType = "LatestTime"
},
SourceSiteOperations = "Required"
}
};
var failoverExecution = client.ReplicationProtectedItem.UnplannedFailover(
vmWareFabric.Name,
containersResponse.ProtectionContainers[0].Name,
protectedItem.Name,
ufoInput,
RequestHeaders);
Assert.NotNull(failoverExecution);
Assert.Equal(OperationStatus.Succeeded, failoverExecution.Status);
}
}
public void InMageReprotectTest()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string vmId = "7192c867-b38e-11e5-af2b-0050569e66ab";
string vmAccount = "vm";
var responseServers = client.Fabrics.List(RequestHeaders);
Assert.True(
responseServers.Fabrics.Count > 0,
"Servers count can't be less than 1");
var vmWareFabric = responseServers.Fabrics.First(
fabric => fabric.Properties.CustomDetails.InstanceType == "VMware");
Assert.NotNull(vmWareFabric);
var vmWareDetails = vmWareFabric.Properties.CustomDetails as VMwareFabricDetails;
Assert.NotNull(vmWareDetails);
var processServer = vmWareDetails.ProcessServers.FirstOrDefault(
ps => ps.FriendlyName.Equals("hikewalr-psjan6"));
Assert.NotNull(processServer);
var masterTargetServer = vmWareDetails.MasterTargetServers.FirstOrDefault();
Assert.NotNull(masterTargetServer);
var runAsAccount = vmWareDetails.RunAsAccounts.First(
account => account.AccountName.Equals(
vmAccount,
StringComparison.InvariantCultureIgnoreCase));
Assert.NotNull(runAsAccount);
string dataStoreName = "datastore-local (1)";
var containersResponse = client.ProtectionContainer.List(
vmWareFabric.Name,
RequestHeaders);
Assert.NotNull(containersResponse);
Assert.True(
containersResponse.ProtectionContainers.Count > 0,
"Containers count can't be less than 1.");
var protectedItemsResponse = client.ReplicationProtectedItem.Get(
vmWareFabric.Name,
containersResponse.ProtectionContainers[0].Name,
vmId + "-Protected",
RequestHeaders);
Assert.NotNull(protectedItemsResponse);
Assert.NotNull(protectedItemsResponse.ReplicationProtectedItem);
var protectedItem = protectedItemsResponse.ReplicationProtectedItem;
Assert.NotNull(protectedItem.Properties.ProviderSpecificDetails);
var vmWareAzureV2Details = protectedItem.Properties.ProviderSpecificDetails
as InMageAzureV2ProviderSpecificSettings;
Assert.NotNull(vmWareAzureV2Details);
var policiesResponse = client.Policies.List(RequestHeaders);
Assert.NotNull(policiesResponse);
Assert.NotEmpty(policiesResponse.Policies);
var policy = policiesResponse.Policies.FirstOrDefault(
p => p.Properties.ProviderSpecificDetails.InstanceType == "InMage");
Assert.NotNull(policy);
ReverseReplicationInput input = new ReverseReplicationInput
{
Properties = new ReverseReplicationInputProperties
{
FailoverDirection = "RecoveryToPrimary",
ProviderSpecificDetails = new InMageReprotectInput
{
DatastoreName = dataStoreName,
DiskExclusionInput = new InMageDiskExclusionInput(),
MasterTargetId = masterTargetServer.Id,
ProcessServerId = processServer.Id,
ProfileId = policy.Id,
RetentionDrive = masterTargetServer.RetentionVolumes.FirstOrDefault().VolumeName,
RunAsAccountId = runAsAccount.AccountId
}
}
};
var reprotectResponse = client.ReplicationProtectedItem.Reprotect(
vmWareFabric.Name,
containersResponse.ProtectionContainers[0].Name,
protectedItem.Name,
input,
RequestHeaders);
Assert.NotNull(reprotectResponse);
Assert.Equal(OperationStatus.Succeeded, reprotectResponse.Status);
}
}
public void InMageAzureV2ReprotectTest()
{
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetSiteRecoveryClient(CustomHttpHandler);
string vmId = "1faecbb8-b47d-11e5-af2b-0050569e66ab";
string vmAccount = "vm";
var responseServers = client.Fabrics.List(RequestHeaders);
Assert.True(
responseServers.Fabrics.Count > 0,
"Servers count can't be less than 1");
var vmWareFabric = responseServers.Fabrics.First(
fabric => fabric.Properties.CustomDetails.InstanceType == "VMware");
Assert.NotNull(vmWareFabric);
var vmWareDetails = vmWareFabric.Properties.CustomDetails as VMwareFabricDetails;
Assert.NotNull(vmWareDetails);
var processServer = vmWareDetails.ProcessServers.FirstOrDefault(
ps => ps.FriendlyName.Equals("hikewalr-cs"));
Assert.NotNull(processServer);
var masterTargetServer = vmWareDetails.MasterTargetServers.FirstOrDefault();
Assert.NotNull(masterTargetServer);
var runAsAccount = vmWareDetails.RunAsAccounts.First(
account => account.AccountName.Equals(
vmAccount,
StringComparison.InvariantCultureIgnoreCase));
Assert.NotNull(runAsAccount);
var containersResponse = client.ProtectionContainer.List(
vmWareFabric.Name,
RequestHeaders);
Assert.NotNull(containersResponse);
Assert.True(
containersResponse.ProtectionContainers.Count > 0,
"Containers count can't be less than 1.");
var protectedItemsResponse = client.ReplicationProtectedItem.Get(
vmWareFabric.Name,
containersResponse.ProtectionContainers[0].Name,
vmId + "-Protected",
RequestHeaders);
Assert.NotNull(protectedItemsResponse);
Assert.NotNull(protectedItemsResponse.ReplicationProtectedItem);
var protectedItem = protectedItemsResponse.ReplicationProtectedItem;
Assert.NotNull(protectedItem.Properties.ProviderSpecificDetails);
var vmWareAzureV2Details = protectedItem.Properties.ProviderSpecificDetails
as InMageProviderSpecificSettings;
Assert.NotNull(vmWareAzureV2Details);
var policiesResponse = client.Policies.List(RequestHeaders);
Assert.NotNull(policiesResponse);
Assert.NotEmpty(policiesResponse.Policies);
var policy = policiesResponse.Policies.FirstOrDefault(
p => p.Properties.ProviderSpecificDetails.InstanceType == "InMageAzureV2");
Assert.NotNull(policy);
string storageAccountId = "/subscriptions/c183865e-6077-46f2-a3b1-deb0f4f4650a/resourceGroups/Default-Storage-WestUS/providers/Microsoft.ClassicStorage/storageAccounts/hikewalrstoragewestus";
ReverseReplicationInput input = new ReverseReplicationInput
{
Properties = new ReverseReplicationInputProperties
{
FailoverDirection = "RecoveryToPrimary",
ProviderSpecificDetails = new InMageAzureV2ReprotectInput
{
MasterTargetId = masterTargetServer.Id,
ProcessServerId = processServer.Id,
PolicyId = policy.Id,
RunAsAccountId = runAsAccount.AccountId,
StorageAccountId = storageAccountId
}
}
};
var reprotectResponse = client.ReplicationProtectedItem.Reprotect(
vmWareFabric.Name,
containersResponse.ProtectionContainers[0].Name,
protectedItem.Name,
input,
RequestHeaders);
Assert.NotNull(reprotectResponse);
Assert.Equal(OperationStatus.Succeeded, reprotectResponse.Status);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Prometheus
{
/// <summary>
/// Base class for metrics, defining the basic informative API and the internal API.
/// </summary>
public abstract class Collector
{
/// <summary>
/// The metric name, e.g. http_requests_total.
/// </summary>
public string Name { get; }
/// <summary>
/// The help text describing the metric for a human audience.
/// </summary>
public string Help { get; }
/// <summary>
/// Names of the instance-specific labels (name-value pairs) that apply to this metric.
/// When the values are added to the names, you get a <see cref="ChildBase"/> instance.
/// </summary>
public string[] LabelNames { get; }
internal abstract Task CollectAndSerializeAsync(IMetricsSerializer serializer, CancellationToken cancel);
// Used by ChildBase.Remove()
internal abstract void RemoveLabelled(Labels labels);
private static readonly string[] EmptyLabelNames = new string[0];
private const string ValidMetricNameExpression = "^[a-zA-Z_:][a-zA-Z0-9_:]*$";
private const string ValidLabelNameExpression = "^[a-zA-Z_:][a-zA-Z0-9_:]*$";
private const string ReservedLabelNameExpression = "^__.*$";
private static readonly Regex MetricNameRegex = new Regex(ValidMetricNameExpression, RegexOptions.Compiled);
private static readonly Regex LabelNameRegex = new Regex(ValidLabelNameExpression, RegexOptions.Compiled);
private static readonly Regex ReservedLabelRegex = new Regex(ReservedLabelNameExpression, RegexOptions.Compiled);
protected Collector(string name, string help, string[]? labelNames)
{
labelNames ??= EmptyLabelNames;
if (!MetricNameRegex.IsMatch(name))
throw new ArgumentException($"Metric name '{name}' does not match regex '{ValidMetricNameExpression}'.");
foreach (var labelName in labelNames)
{
if (labelName == null)
throw new ArgumentNullException("Label name was null.");
ValidateLabelName(labelName);
}
Name = name;
Help = help;
LabelNames = labelNames;
}
internal static void ValidateLabelName(string labelName)
{
if (!LabelNameRegex.IsMatch(labelName))
throw new ArgumentException($"Label name '{labelName}' does not match regex '{ValidLabelNameExpression}'.");
if (ReservedLabelRegex.IsMatch(labelName))
throw new ArgumentException($"Label name '{labelName}' is not valid - labels starting with double underscore are reserved!");
}
}
/// <summary>
/// Base class for metrics collectors, providing common labeled child management functionality.
/// </summary>
public abstract class Collector<TChild> : Collector, ICollector<TChild>
where TChild : ChildBase
{
private readonly ConcurrentDictionary<Labels, TChild> _labelledMetrics = new ConcurrentDictionary<Labels, TChild>();
// Lazy-initialized since not every collector will use a child with no labels.
private readonly Lazy<TChild> _unlabelledLazy;
/// <summary>
/// Gets the child instance that has no labels.
/// </summary>
protected internal TChild Unlabelled => _unlabelledLazy.Value;
// We need it for the ICollector interface but using this is rarely relevant in client code, so keep it obscured.
TChild ICollector<TChild>.Unlabelled => Unlabelled;
// This servers a slightly silly but useful purpose: by default if you start typing .La... and trigger Intellisense
// it will often for whatever reason focus on LabelNames instead of Labels, leading to tiny but persistent frustration.
// Having WithLabels() instead eliminates the other candidate and allows for a frustration-free typing experience.
public TChild WithLabels(params string[] labelValues) => Labels(labelValues);
// Discourage it as it can create confusion. But it works fine, so no reason to mark it obsolete, really.
[EditorBrowsable(EditorBrowsableState.Never)]
public TChild Labels(params string[] labelValues)
{
var key = new Labels(LabelNames, labelValues);
return GetOrAddLabelled(key);
}
public void RemoveLabelled(params string[] labelValues)
{
var key = new Labels(LabelNames, labelValues);
_labelledMetrics.TryRemove(key, out _);
}
internal override void RemoveLabelled(Labels labels)
{
_labelledMetrics.TryRemove(labels, out _);
}
/// <summary>
/// Gets the instance-specific label values of all labelled instances of the collector.
/// Values of any inherited static labels are not returned in the result.
///
/// Note that during concurrent operation, the set of values returned here
/// may diverge from the latest set of values used by the collector.
/// </summary>
public IEnumerable<string[]> GetAllLabelValues()
{
foreach (var labels in _labelledMetrics.Keys)
{
if (labels.Count == 0)
continue; // We do not return the "unlabelled" label set.
// Defensive copy.
yield return labels.Values.ToArray();
}
}
/// <summary>
/// Set of static labels obtained from any hierarchy level (either defined in metric configuration or in registry).
/// </summary>
private readonly Labels _staticLabels;
private TChild GetOrAddLabelled(Labels key)
{
// Don't allocate lambda for GetOrAdd in the common case that the labeled metrics exist.
if (_labelledMetrics.TryGetValue(key, out var metric))
return metric;
return _labelledMetrics.GetOrAdd(key, k => NewChild(k, k.Concat(_staticLabels), publish: !_suppressInitialValue));
}
/// <summary>
/// For tests that want to see what label values were used when metrics were created.
/// </summary>
internal Labels[] GetAllLabels() => _labelledMetrics.Select(p => p.Key).ToArray();
internal Collector(string name, string help, string[]? labelNames, Labels staticLabels, bool suppressInitialValue)
: base(name, help, labelNames)
{
_staticLabels = staticLabels;
_suppressInitialValue = suppressInitialValue;
_unlabelledLazy = new Lazy<TChild>(() => GetOrAddLabelled(Prometheus.Labels.Empty));
// Check for label name collisions.
var allLabelNames = (labelNames ?? new string[0]).Concat(staticLabels.Names).ToList();
if (allLabelNames.Count() != allLabelNames.Distinct(StringComparer.Ordinal).Count())
throw new InvalidOperationException("The set of label names includes duplicates: " + string.Join(", ", allLabelNames));
_familyHeaderLines = new byte[][]
{
PrometheusConstants.ExportEncoding.GetBytes($"# HELP {name} {help}"),
PrometheusConstants.ExportEncoding.GetBytes($"# TYPE {name} {Type.ToString().ToLowerInvariant()}")
};
}
/// <summary>
/// Creates a new instance of the child collector type.
/// </summary>
private protected abstract TChild NewChild(Labels labels, Labels flattenedLabels, bool publish);
private protected abstract MetricType Type { get; }
private readonly byte[][] _familyHeaderLines;
internal override async Task CollectAndSerializeAsync(IMetricsSerializer serializer, CancellationToken cancel)
{
EnsureUnlabelledMetricCreatedIfNoLabels();
await serializer.WriteFamilyDeclarationAsync(_familyHeaderLines, cancel);
foreach (var child in _labelledMetrics.Values)
await child.CollectAndSerializeAsync(serializer, cancel);
}
private readonly bool _suppressInitialValue;
private void EnsureUnlabelledMetricCreatedIfNoLabels()
{
// We want metrics to exist even with 0 values if they are supposed to be used without labels.
// Labelled metrics are created when label values are assigned. However, as unlabelled metrics are lazy-created
// (they might are optional if labels are used) we might lose them for cases where they really are desired.
// If there are no label names then clearly this metric is supposed to be used unlabelled, so create it.
// Otherwise, we allow unlabelled metrics to be used if the user explicitly does it but omit them by default.
if (!_unlabelledLazy.IsValueCreated && !LabelNames.Any())
GetOrAddLabelled(Prometheus.Labels.Empty);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Services.WebApi;
using Newtonsoft.Json.Linq;
namespace Microsoft.VisualStudio.Services.Agent.Util
{
public static class VarUtil
{
public static StringComparer EnvironmentVariableKeyComparer
{
get
{
if (PlatformUtil.RunningOnWindows)
{
return StringComparer.OrdinalIgnoreCase;
}
return StringComparer.Ordinal;
}
}
public static string OS
{
get
{
switch (PlatformUtil.HostOS)
{
case PlatformUtil.OS.Linux:
return "Linux";
case PlatformUtil.OS.OSX:
return "Darwin";
case PlatformUtil.OS.Windows:
return Environment.GetEnvironmentVariable("OS");
default:
throw new NotSupportedException(); // Should never reach here.
}
}
}
public static string OSArchitecture
{
get
{
switch (PlatformUtil.HostArchitecture)
{
case Architecture.X86:
return "X86";
case Architecture.X64:
return "X64";
case Architecture.Arm:
return "ARM";
case Architecture.Arm64:
return "ARM64";
default:
throw new NotSupportedException(); // Should never reach here.
}
}
}
public static JToken ExpandEnvironmentVariables(IHostContext context, JToken target)
{
var mapFuncs = new Dictionary<JTokenType, Func<JToken, JToken>>
{
{
JTokenType.String,
(t)=> {
var token = new Dictionary<string, string>()
{
{
"token", t.ToString()
}
};
ExpandEnvironmentVariables(context, token);
return token["token"];
}
}
};
return target.Map(mapFuncs);
}
public static void ExpandEnvironmentVariables(IHostContext context, IDictionary<string, string> target)
{
ArgUtil.NotNull(context, nameof(context));
Tracing trace = context.GetTrace(nameof(VarUtil));
trace.Entering();
// Copy the environment variables into a dictionary that uses the correct comparer.
var source = new Dictionary<string, string>(EnvironmentVariableKeyComparer);
IDictionary environment = Environment.GetEnvironmentVariables();
foreach (DictionaryEntry entry in environment)
{
string key = entry.Key as string ?? string.Empty;
string val = entry.Value as string ?? string.Empty;
source[key] = val;
}
// Expand the target values.
ExpandValues(context, source, target);
}
public static JToken ExpandValues(IHostContext context, IDictionary<string, string> source, JToken target)
{
var mapFuncs = new Dictionary<JTokenType, Func<JToken, JToken>>
{
{
JTokenType.String,
(t)=> {
var token = new Dictionary<string, string>()
{
{
"token", t.ToString()
}
};
ExpandValues(context, source, token);
return token["token"];
}
}
};
return target.Map(mapFuncs);
}
public static void ExpandValues(IHostContext context, IDictionary<string, string> source, IDictionary<string, string> target)
{
ArgUtil.NotNull(context, nameof(context));
ArgUtil.NotNull(source, nameof(source));
Tracing trace = context.GetTrace(nameof(VarUtil));
trace.Entering();
target = target ?? new Dictionary<string, string>();
// This algorithm does not perform recursive replacement.
// Process each key in the target dictionary.
foreach (string targetKey in target.Keys.ToArray())
{
trace.Verbose($"Processing expansion for: '{targetKey}'");
int startIndex = 0;
int prefixIndex;
int suffixIndex;
string targetValue = target[targetKey] ?? string.Empty;
// Find the next macro within the target value.
while (startIndex < targetValue.Length &&
(prefixIndex = targetValue.IndexOf(Constants.Variables.MacroPrefix, startIndex, StringComparison.Ordinal)) >= 0 &&
(suffixIndex = targetValue.IndexOf(Constants.Variables.MacroSuffix, prefixIndex + Constants.Variables.MacroPrefix.Length, StringComparison.Ordinal)) >= 0)
{
// A candidate was found.
string variableKey = targetValue.Substring(
startIndex: prefixIndex + Constants.Variables.MacroPrefix.Length,
length: suffixIndex - prefixIndex - Constants.Variables.MacroPrefix.Length);
trace.Verbose($"Found macro candidate: '{variableKey}'");
string variableValue;
if (!string.IsNullOrEmpty(variableKey) &&
TryGetValue(trace, source, variableKey, out variableValue))
{
// A matching variable was found.
// Update the target value.
trace.Verbose("Macro found.");
targetValue = string.Concat(
targetValue.Substring(0, prefixIndex),
variableValue ?? string.Empty,
targetValue.Substring(suffixIndex + Constants.Variables.MacroSuffix.Length));
// Bump the start index to prevent recursive replacement.
startIndex = prefixIndex + (variableValue ?? string.Empty).Length;
}
else
{
// A matching variable was not found.
trace.Verbose("Macro not found.");
startIndex = prefixIndex + 1;
}
}
target[targetKey] = targetValue ?? string.Empty;
}
}
private static bool TryGetValue(Tracing trace, IDictionary<string, string> source, string name, out string val)
{
if (source.TryGetValue(name, out val))
{
val = val ?? string.Empty;
trace.Verbose($"Get '{name}': '{val}'");
return true;
}
val = null;
trace.Verbose($"Get '{name}' (not found)");
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.Diagnostics;
using System.Collections;
using System.Globalization;
using System.DirectoryServices;
using System.Net;
using System.Threading;
/// This is a class designed to cache DirectoryEntires instead of creating them every time.
namespace System.DirectoryServices.AccountManagement
{
internal class SDSCache
{
public static SDSCache Domain
{
get
{
return SDSCache.s_domainCache;
}
}
public static SDSCache LocalMachine
{
get
{
return SDSCache.s_localMachineCache;
}
}
private static SDSCache s_domainCache = new SDSCache(false);
private static SDSCache s_localMachineCache = new SDSCache(true);
[System.Security.SecurityCritical]
public PrincipalContext GetContext(string name, NetCred credentials, ContextOptions contextOptions)
{
string contextName = name;
string userName = null;
bool explicitCreds = false;
if (credentials != null && credentials.UserName != null)
{
if (credentials.Domain != null)
userName = credentials.Domain + "\\" + credentials.UserName;
else
userName = credentials.UserName;
explicitCreds = true;
}
else
{
userName = Utils.GetNT4UserName();
}
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: looking for context for server {0}, user {1}, explicitCreds={2}, options={3}",
name,
userName,
explicitCreds.ToString(),
contextOptions.ToString());
if (!_isSAM)
{
// Determine the domain DNS name
// DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY
int flags = unchecked((int)(0x40000000 | 0x00000010 | 0x00000100));
UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, contextName, null, flags);
contextName = info.DomainName;
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: final contextName is " + contextName);
ManualResetEvent contextReadyEvent = null;
while (true)
{
Hashtable credTable = null;
PrincipalContext ctx = null;
// Wait for the PrincipalContext to be ready
if (contextReadyEvent != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: waiting");
contextReadyEvent.WaitOne();
}
contextReadyEvent = null;
lock (_tableLock)
{
CredHolder credHolder = (CredHolder)_table[contextName];
if (credHolder != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: found a credHolder for " + contextName);
credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds);
Debug.Assert(credTable != null);
object o = credTable[userName];
if (o is Placeholder)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: credHolder for " + contextName + " has a Placeholder");
// A PrincipalContext is currently being constructed by another thread.
// Wait for it.
contextReadyEvent = ((Placeholder)o).contextReadyEvent;
continue;
}
WeakReference refToContext = o as WeakReference;
if (refToContext != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is non-null");
ctx = (PrincipalContext)refToContext.Target; // null if GC'ed
// If the PrincipalContext hasn't been GCed or disposed, use it.
// Otherwise, we'll need to create a new one
if (ctx != null && ctx.Disposed == false)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: using found refToContext");
return ctx;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is GCed/disposed, removing");
credTable.Remove(userName);
}
}
}
// Either credHolder/credTable are null (no contexts exist for the contextName), or credHolder/credTable
// are non-null (contexts exist, but none for the userName). Either way, we need to create a PrincipalContext.
if (credHolder == null)
{
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: null credHolder for " + contextName + ", explicitCreds=" + explicitCreds.ToString());
// No contexts exist for the contextName. Create a CredHolder for the contextName so we have a place
// to store the PrincipalContext we'll be creating.
credHolder = new CredHolder();
_table[contextName] = credHolder;
credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds);
}
// Put a placeholder on the contextName/userName slot, so that other threads that come along after
// we release the tableLock know we're in the process of creating the needed PrincipalContext and will wait for us
credTable[userName] = new Placeholder();
}
// Now we just need to create a PrincipalContext for the contextName and credentials
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: creating context, contextName=" + contextName + ", options=" + contextOptions.ToString());
ctx = new PrincipalContext(
(_isSAM ? ContextType.Machine : ContextType.Domain),
contextName,
null,
contextOptions,
(credentials != null ? credentials.UserName : null),
(credentials != null ? credentials.Password : null)
);
lock (_tableLock)
{
Placeholder placeHolder = (Placeholder)credTable[userName];
// Replace the placeholder with the newly-created PrincipalContext
credTable[userName] = new WeakReference(ctx);
// Signal waiting threads to continue. We do this after inserting the PrincipalContext
// into the table, so that the PrincipalContext is ready as soon as the other threads wake up.
// (Actually, the order probably doesn't matter, since even if we did it in the
// opposite order and the other thread woke up before we inserted the PrincipalContext, it would
// just block as soon as it tries to acquire the tableLock that we're currently holding.)
bool f = placeHolder.contextReadyEvent.Set();
Debug.Assert(f == true);
}
return ctx;
}
}
//
private SDSCache(bool isSAM)
{
_isSAM = isSAM;
}
private Hashtable _table = new Hashtable();
private object _tableLock = new object();
private bool _isSAM;
private class CredHolder
{
public Hashtable explicitCreds = new Hashtable();
public Hashtable defaultCreds = new Hashtable();
}
private class Placeholder
{
// initially non-signaled
public ManualResetEvent contextReadyEvent = new ManualResetEvent(false);
}
}
}
| |
#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.Globalization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Schema;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text;
using Extensions=Newtonsoft.Json.Schema.Extensions;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaGeneratorTests : TestFixtureBase
{
[Test]
public void Generate_GenericDictionary()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof (Dictionary<string, List<string>>));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": [
""array"",
""null""
],
""items"": {
""type"": [
""string"",
""null""
]
}
}
}", json);
Dictionary<string, List<string>> value = new Dictionary<string, List<string>>
{
{"HasValue", new List<string>() { "first", "second", null }},
{"NoValue", null}
};
string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented);
JObject o = JObject.Parse(valueJson);
Assert.IsTrue(o.IsValid(schema));
}
#if !(NETFX_CORE || PORTABLE)
[Test]
public void Generate_DefaultValueAttributeTestClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass));
string json = schema.ToString();
Assert.AreEqual(@"{
""description"": ""DefaultValueAttributeTestClass description!"",
""type"": ""object"",
""additionalProperties"": false,
""properties"": {
""TestField1"": {
""required"": true,
""type"": ""integer"",
""default"": 21
},
""TestProperty1"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""TestProperty1Value""
}
}
}", json);
}
#endif
[Test]
public void Generate_Person()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Person));
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""Person"",
""title"": ""Title!"",
""description"": ""JsonObjectAttribute description!"",
""type"": ""object"",
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""BirthDate"": {
""required"": true,
""type"": ""string""
},
""LastModified"": {
""required"": true,
""type"": ""string""
}
}
}", json);
}
[Test]
public void Generate_UserNullable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(UserNullable));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Id"": {
""required"": true,
""type"": ""string""
},
""FName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""LName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""RoleId"": {
""required"": true,
""type"": ""integer""
},
""NullableRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""NullRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""Active"": {
""required"": true,
""type"": [
""boolean"",
""null""
]
}
}
}", json);
}
[Test]
public void Generate_RequiredMembersClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(RequiredMembersClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type);
}
[Test]
public void Generate_Store()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(11, schema.Properties.Count);
JsonSchema productArraySchema = schema.Properties["product"];
JsonSchema productSchema = productArraySchema.Items[0];
Assert.AreEqual(4, productSchema.Properties.Count);
}
[Test]
public void MissingSchemaIdHandlingTest()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(null, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
schema = generator.Generate(typeof (Store));
Assert.AreEqual(typeof(Store).FullName, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id);
}
[Test]
public void CircularReferenceError()
{
ExceptionAssert.Throws<Exception>(@"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.",
() =>
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
});
}
[Test]
public void CircularReferenceWithTypeNameId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void CircularReferenceWithExplicitId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass));
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type);
Assert.AreEqual("MyExplicitId", schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void GenerateSchemaForType()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Type));
Assert.AreEqual(JsonSchemaType.String, schema.Type);
string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented);
JValue v = new JValue(json);
Assert.IsTrue(v.IsValid(schema));
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
[Test]
public void GenerateSchemaForISerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Exception));
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(true, schema.AllowAdditionalProperties);
Assert.AreEqual(null, schema.Properties);
}
#endif
#if !(NETFX_CORE || PORTABLE)
[Test]
public void GenerateSchemaForDBNull()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(DBNull));
Assert.AreEqual(JsonSchemaType.Null, schema.Type);
}
public class CustomDirectoryInfoMapper : DefaultContractResolver
{
public CustomDirectoryInfoMapper()
: base(true)
{
}
protected override JsonContract CreateContract(Type objectType)
{
if (objectType == typeof(DirectoryInfo))
return base.CreateObjectContract(objectType);
return base.CreateContract(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
JsonPropertyCollection c = new JsonPropertyCollection(type);
CollectionUtils.AddRange(c, (IEnumerable)properties.Where(m => m.PropertyName != "Root"));
return c;
}
}
[Test]
public void GenerateSchemaForDirectoryInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CustomDirectoryInfoMapper
{
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.IO.DirectoryInfo"",
""required"": true,
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""Parent"": {
""$ref"": ""System.IO.DirectoryInfo""
},
""Exists"": {
""required"": true,
""type"": ""boolean""
},
""FullName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""Extension"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""CreationTime"": {
""required"": true,
""type"": ""string""
},
""CreationTimeUtc"": {
""required"": true,
""type"": ""string""
},
""LastAccessTime"": {
""required"": true,
""type"": ""string""
},
""LastAccessTimeUtc"": {
""required"": true,
""type"": ""string""
},
""LastWriteTime"": {
""required"": true,
""type"": ""string""
},
""LastWriteTimeUtc"": {
""required"": true,
""type"": ""string""
},
""Attributes"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
DirectoryInfo temp = new DirectoryInfo(@"c:\temp");
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.ContractResolver = new CustomDirectoryInfoMapper
{
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
IgnoreSerializableInterface = true
#endif
};
serializer.Serialize(jsonWriter, temp);
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
}
#endif
[Test]
public void GenerateSchemaCamelCase()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CamelCasePropertyNamesContractResolver()
{
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof(Version), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""major"": {
""required"": true,
""type"": ""integer""
},
""minor"": {
""required"": true,
""type"": ""integer""
},
""build"": {
""required"": true,
""type"": ""integer""
},
""revision"": {
""required"": true,
""type"": ""integer""
},
""majorRevision"": {
""required"": true,
""type"": ""integer""
},
""minorRevision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
[Test]
public void GenerateSchemaSerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.ContractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
};
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof (Version), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""_Major"": {
""required"": true,
""type"": ""integer""
},
""_Minor"": {
""required"": true,
""type"": ""integer""
},
""_Build"": {
""required"": true,
""type"": ""integer""
},
""_Revision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
};
serializer.Serialize(jsonWriter, new Version(1, 2, 3, 4));
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
Assert.AreEqual(@"{
""_Major"": 1,
""_Minor"": 2,
""_Build"": 3,
""_Revision"": 4
}", jsonWriter.Token.ToString());
Version version = jsonWriter.Token.ToObject<Version>(serializer);
Assert.AreEqual(1, version.Major);
Assert.AreEqual(2, version.Minor);
Assert.AreEqual(3, version.Build);
Assert.AreEqual(4, version.Revision);
}
#endif
public enum SortTypeFlag
{
No = 0,
Asc = 1,
Desc = -1
}
public class X
{
public SortTypeFlag x;
}
[Test]
public void GenerateSchemaWithNegativeEnum()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""x"": {
""required"": true,
""type"": ""integer"",
""enum"": [
0,
1,
-1
],
""options"": [
{
""value"": 0,
""label"": ""No""
},
{
""value"": 1,
""label"": ""Asc""
},
{
""value"": -1,
""label"": ""Desc""
}
]
}
}
}", json);
}
[Test]
public void CircularCollectionReferences()
{
Type type = typeof (Workspace);
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type);
// should succeed
Assert.IsNotNull(jsonSchema);
}
[Test]
public void CircularReferenceWithMixedRequires()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass));
string json = jsonSchema.ToString();
Assert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"",
""type"": [
""object"",
""null""
],
""properties"": {
""Name"": {
""required"": true,
""type"": ""string""
},
""Child"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass""
}
}
}", json);
}
[Test]
public void JsonPropertyWithHandlingValues()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues));
string json = jsonSchema.ToString();
Assert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"",
""required"": true,
""type"": [
""object"",
""null""
],
""properties"": {
""DefaultValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingPopulateProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIgnoreAndPopulateProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""NullValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
]
},
""NullValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""ReferenceLoopHandlingErrorProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingIgnoreProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingSerializeProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
}
}
}", json);
}
[Test]
public void GenerateForNullableInt32()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass));
string json = jsonSchema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Value"": {
""required"": true,
""type"": [
""integer"",
""null""
]
}
}
}", json);
}
}
public class NullableInt32TestClass
{
public int? Value { get; set; }
}
public class DMDSLBase
{
public String Comment;
}
public class Workspace : DMDSLBase
{
public ControlFlowItemCollection Jobs = new ControlFlowItemCollection();
}
public class ControlFlowItemBase : DMDSLBase
{
public String Name;
}
public class ControlFlowItem : ControlFlowItemBase//A Job
{
public TaskCollection Tasks = new TaskCollection();
public ContainerCollection Containers = new ContainerCollection();
}
public class ControlFlowItemCollection : List<ControlFlowItem>
{
}
public class Task : ControlFlowItemBase
{
public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection();
public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection();
}
public class TaskCollection : List<Task>
{
}
public class Container : ControlFlowItemBase
{
public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection();
}
public class ContainerCollection : List<Container>
{
}
public class DataFlowTask_DSL : ControlFlowItemBase
{
}
public class DataFlowTaskCollection : List<DataFlowTask_DSL>
{
}
public class SequenceContainer_DSL : Container
{
}
public class BulkInsertTaskCollection : List<BulkInsertTask_DSL>
{
}
public class BulkInsertTask_DSL
{
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.ElasticSearch;
using ASC.Projects.Core.DataInterfaces;
using ASC.Projects.Core.Domain;
using ASC.Projects.Core.Services.NotifyService;
using ASC.Web.Projects.Core.Engine;
using ASC.Web.Projects.Core.Search;
namespace ASC.Projects.Engine
{
public class MilestoneEngine
{
public IDaoFactory DaoFactory { get; set; }
public ProjectSecurity ProjectSecurity { get; set; }
public bool DisableNotifications { get; set; }
#region Get Milestones
public MilestoneEngine(bool disableNotifications)
{
DisableNotifications = disableNotifications;
}
public IEnumerable<Milestone> GetAll()
{
return DaoFactory.MilestoneDao.GetAll().Where(CanRead);
}
public List<Milestone> GetByFilter(TaskFilter filter)
{
var listMilestones = new List<Milestone>();
var anyOne = ProjectSecurity.IsPrivateDisabled;
var isAdmin = ProjectSecurity.CurrentUserAdministrator;
while (true)
{
var milestones = DaoFactory.MilestoneDao.GetByFilter(filter, isAdmin, anyOne);
if (filter.LastId != 0)
{
var lastMilestoneIndex = milestones.FindIndex(r => r.ID == filter.LastId);
if (lastMilestoneIndex >= 0)
{
milestones = milestones.SkipWhile((r, index) => index <= lastMilestoneIndex).ToList();
}
}
listMilestones.AddRange(milestones);
if (filter.Max <= 0 || filter.Max > 150000) break;
listMilestones = listMilestones.Take((int)filter.Max).ToList();
if (listMilestones.Count == filter.Max || milestones.Count == 0) break;
if (listMilestones.Count != 0)
filter.LastId = listMilestones.Last().ID;
filter.Offset += filter.Max;
}
return listMilestones;
}
public int GetByFilterCount(TaskFilter filter)
{
return DaoFactory.MilestoneDao.GetByFilterCount(filter, ProjectSecurity.CurrentUserAdministrator, ProjectSecurity.IsPrivateDisabled);
}
public List<Tuple<Guid, int, int>> GetByFilterCountForReport(TaskFilter filter)
{
return DaoFactory.MilestoneDao.GetByFilterCountForReport(filter, ProjectSecurity.CurrentUserAdministrator, ProjectSecurity.IsPrivateDisabled);
}
public List<Milestone> GetByProject(int projectId)
{
var milestones = DaoFactory.MilestoneDao.GetByProject(projectId).Where(CanRead).ToList();
milestones.Sort((x, y) =>
{
if (x.Status != y.Status) return x.Status.CompareTo(y.Status);
if (x.Status == MilestoneStatus.Open) return x.DeadLine.CompareTo(y.DeadLine);
return y.DeadLine.CompareTo(x.DeadLine);
});
return milestones;
}
public List<Milestone> GetByStatus(int projectId, MilestoneStatus milestoneStatus)
{
var milestones = DaoFactory.MilestoneDao.GetByStatus(projectId, milestoneStatus).Where(CanRead).ToList();
milestones.Sort((x, y) =>
{
if (x.Status != y.Status) return x.Status.CompareTo(y.Status);
if (x.Status == MilestoneStatus.Open) return x.DeadLine.CompareTo(y.DeadLine);
return y.DeadLine.CompareTo(x.DeadLine);
});
return milestones;
}
public List<Milestone> GetUpcomingMilestones(int max, params int[] projects)
{
var offset = 0;
var milestones = new List<Milestone>();
while (true)
{
var packet = DaoFactory.MilestoneDao.GetUpcomingMilestones(offset, 2 * max, projects);
milestones.AddRange(packet.Where(CanRead));
if (max <= milestones.Count || packet.Count() < 2 * max)
{
break;
}
offset += 2 * max;
}
return milestones.Count <= max ? milestones : milestones.GetRange(0, max);
}
public List<Milestone> GetLateMilestones(int max)
{
var offset = 0;
var milestones = new List<Milestone>();
while (true)
{
var packet = DaoFactory.MilestoneDao.GetLateMilestones(offset, 2 * max);
milestones.AddRange(packet.Where(CanRead));
if (max <= milestones.Count || packet.Count() < 2 * max)
{
break;
}
offset += 2 * max;
}
return milestones.Count <= max ? milestones : milestones.GetRange(0, max);
}
public List<Milestone> GetByDeadLine(DateTime deadline)
{
return DaoFactory.MilestoneDao.GetByDeadLine(deadline).Where(CanRead).ToList();
}
public Milestone GetByID(int id)
{
return GetByID(id, true);
}
public Milestone GetByID(int id, bool checkSecurity)
{
var m = DaoFactory.MilestoneDao.GetById(id);
if (!checkSecurity)
return m;
return CanRead(m) ? m : null;
}
public bool IsExists(int id)
{
return GetByID(id) != null;
}
public string GetLastModified()
{
return DaoFactory.MilestoneDao.GetLastModified();
}
private bool CanRead(Milestone m)
{
return ProjectSecurity.CanRead(m);
}
#endregion
#region Save, Delete, Notify
public Milestone SaveOrUpdate(Milestone milestone)
{
return SaveOrUpdate(milestone, false, false);
}
public Milestone SaveOrUpdate(Milestone milestone, bool notifyResponsible)
{
return SaveOrUpdate(milestone, notifyResponsible, false);
}
public Milestone SaveOrUpdate(Milestone milestone, bool notifyResponsible, bool import)
{
if (milestone == null) throw new ArgumentNullException("milestone");
if (milestone.Project == null) throw new Exception("milestone.project is null");
if (milestone.Responsible.Equals(Guid.Empty)) throw new Exception("milestone.responsible is empty");
// check guest responsible
if (ProjectSecurity.IsVisitor(milestone.Responsible))
{
ProjectSecurity.CreateGuestSecurityException();
}
milestone.LastModifiedBy = SecurityContext.CurrentAccount.ID;
milestone.LastModifiedOn = TenantUtil.DateTimeNow();
var isNew = milestone.ID == default(int);//Task is new
var oldResponsible = Guid.Empty;
if (isNew)
{
if (milestone.CreateBy == default(Guid)) milestone.CreateBy = SecurityContext.CurrentAccount.ID;
if (milestone.CreateOn == default(DateTime)) milestone.CreateOn = TenantUtil.DateTimeNow();
ProjectSecurity.DemandCreate<Milestone>(milestone.Project);
milestone = DaoFactory.MilestoneDao.Save(milestone);
}
else
{
var oldMilestone = DaoFactory.MilestoneDao.GetById(new[] { milestone.ID }).FirstOrDefault();
if (oldMilestone == null) throw new ArgumentNullException("milestone");
oldResponsible = oldMilestone.Responsible;
ProjectSecurity.DemandEdit(milestone);
milestone = DaoFactory.MilestoneDao.Save(milestone);
}
if (!milestone.Responsible.Equals(Guid.Empty))
NotifyMilestone(milestone, notifyResponsible, isNew, oldResponsible);
FactoryIndexer<MilestonesWrapper>.IndexAsync(milestone);
return milestone;
}
public Milestone ChangeStatus(Milestone milestone, MilestoneStatus newStatus)
{
ProjectSecurity.DemandEdit(milestone);
if (milestone == null) throw new ArgumentNullException("milestone");
if (milestone.Project == null) throw new Exception("Project can be null.");
if (milestone.Status == newStatus) return milestone;
if (milestone.Project.Status == ProjectStatus.Closed) throw new Exception(EngineResource.ProjectClosedError);
if (milestone.ActiveTaskCount != 0 && newStatus == MilestoneStatus.Closed) throw new Exception("Can not close a milestone with open tasks");
milestone.Status = newStatus;
milestone.LastModifiedBy = SecurityContext.CurrentAccount.ID;
milestone.LastModifiedOn = TenantUtil.DateTimeNow();
milestone.StatusChangedOn = TenantUtil.DateTimeNow();
var senders = new HashSet<Guid> { milestone.Project.Responsible, milestone.CreateBy, milestone.Responsible };
if (newStatus == MilestoneStatus.Closed && !false && senders.Count != 0)
{
NotifyClient.Instance.SendAboutMilestoneClosing(senders, milestone);
}
if (newStatus == MilestoneStatus.Open && !false && senders.Count != 0)
{
NotifyClient.Instance.SendAboutMilestoneResumed(senders, milestone);
}
return DaoFactory.MilestoneDao.Save(milestone);
}
private void NotifyMilestone(Milestone milestone, bool notifyResponsible, bool isNew, Guid oldResponsible)
{
//Don't send anything if notifications are disabled
if (DisableNotifications) return;
if (isNew && milestone.Project.Responsible != SecurityContext.CurrentAccount.ID && !milestone.Project.Responsible.Equals(milestone.Responsible))
{
NotifyClient.Instance.SendAboutMilestoneCreating(new List<Guid> { milestone.Project.Responsible }, milestone);
}
if (notifyResponsible && milestone.Responsible != SecurityContext.CurrentAccount.ID)
{
if (isNew || !oldResponsible.Equals(milestone.Responsible))
NotifyClient.Instance.SendAboutResponsibleByMilestone(milestone);
else
NotifyClient.Instance.SendAboutMilestoneEditing(milestone);
}
}
public void Delete(Milestone milestone)
{
if (milestone == null) throw new ArgumentNullException("milestone");
ProjectSecurity.DemandDelete(milestone);
DaoFactory.MilestoneDao.Delete(milestone.ID);
var users = new HashSet<Guid> { milestone.Project.Responsible, milestone.Responsible };
NotifyClient.Instance.SendAboutMilestoneDeleting(users, milestone);
FactoryIndexer<MilestonesWrapper>.DeleteAsync(milestone);
}
#endregion
}
}
| |
using Signum.Engine.Linq;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.Utilities.Reflection;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
namespace Signum.Engine.Authorization;
public static partial class TypeAuthLogic
{
static readonly Variable<bool> queryFilterDisabled = Statics.ThreadVariable<bool>("queryFilterDisabled");
public static IDisposable? DisableQueryFilter()
{
if (queryFilterDisabled.Value) return null;
queryFilterDisabled.Value = true;
return new Disposable(() => queryFilterDisabled.Value = false);
}
public static bool InSave => inSave.Value;//Available for Type Condition definition
static readonly Variable<bool> inSave = Statics.ThreadVariable<bool>("inSave");
static IDisposable? OnInSave()
{
if (inSave.Value) return null;
inSave.Value = true;
return new Disposable(() => inSave.Value = false);
}
public static Type? IsDelete => isDelete.Value;
static readonly Variable<Type?> isDelete = Statics.ThreadVariable<Type?>("isDelete");
static IDisposable? OnIsDelete(Type type)
{
var oldType = isDelete.Value;
isDelete.Value = type;
return new Disposable(() => isDelete.Value = type);
}
const string CreatedKey = "Created";
const string ModifiedKey = "Modified";
static void Schema_Saving_Instance(Entity ident)
{
if (ident.IsNew)
{
var created = (List<Entity>)Transaction.UserData.GetOrCreate(CreatedKey, () => new List<Entity>());
if (created.Contains(ident))
return;
created.Add(ident);
}
else
{
if (IsCreatedOrModified(Transaction.TopParentUserData(), ident) ||
IsCreatedOrModified(Transaction.UserData, ident))
return;
var modified = (List<Entity>)Transaction.UserData.GetOrCreate(ModifiedKey, () => new List<Entity>());
modified.Add(ident);
}
Transaction.PreRealCommit -= Transaction_PreRealCommit;
Transaction.PreRealCommit += Transaction_PreRealCommit;
}
private static bool IsCreatedOrModified(Dictionary<string, object> dictionary, Entity ident)
{
var modified = (List<Entity>?)dictionary.TryGetC(ModifiedKey);
if (modified != null && modified.Contains(ident))
return true;
var created = (List<Entity>?)dictionary.TryGetC(CreatedKey);
if (created != null && created.Contains(ident))
return true;
return false;
}
public static void RemovePreRealCommitChecking(Entity entity)
{
var created = (List<Entity>?)Transaction.UserData.TryGetC(CreatedKey);
if (created != null && created.Contains(entity))
created.Remove(entity);
var modified = (List<Entity>?)Transaction.UserData.TryGetC(ModifiedKey);
if (modified != null && modified.Contains(entity))
modified.Remove(entity);
}
static void Transaction_PreRealCommit(Dictionary<string, object> dic)
{
using (OnInSave())
{
var modified = (List<Entity>?)dic.TryGetC(ModifiedKey);
if (modified.HasItems())
{
var groups = modified.GroupBy(e => e.GetType(), e => e.Id);
//Assert before
using (var tr = Transaction.ForceNew())
{
foreach (var gr in groups)
miAssertAllowed.GetInvoker(gr.Key)(gr.ToArray(), TypeAllowedBasic.Write);
tr.Commit();
}
//Assert after
foreach (var gr in groups)
{
miAssertAllowed.GetInvoker(gr.Key)(gr.ToArray(), TypeAllowedBasic.Write);
}
}
var created = (List<Entity>?)Transaction.UserData.TryGetC(CreatedKey);
if (created.HasItems())
{
var groups = created.GroupBy(e => e.GetType(), e => e.Id);
//Assert after
foreach (var gr in groups)
miAssertAllowed.GetInvoker(gr.Key)(gr.ToArray(), TypeAllowedBasic.Write);
}
}
}
static GenericInvoker<Action<PrimaryKey[], TypeAllowedBasic>> miAssertAllowed =
new((a, tab) => AssertAllowed<Entity>(a, tab));
static void AssertAllowed<T>(PrimaryKey[] requested, TypeAllowedBasic typeAllowed)
where T : Entity
{
using (DisableQueryFilter())
{
var found = requested.Chunk(1000).SelectMany(gr => Database.Query<T>().Where(a => gr.Contains(a.Id)).Select(a => new
{
a.Id,
Allowed = a.IsAllowedFor(typeAllowed, ExecutionMode.InUserInterface),
})).ToArray();
if (found.Length != requested.Length)
throw new EntityNotFoundException(typeof(T), requested.Except(found.Select(a => a.Id)).ToArray());
PrimaryKey[] notFound = found.Where(a => !a.Allowed).Select(a => a.Id).ToArray();
if (notFound.Any())
{
List<DebugData> debugInfo = Database.Query<T>().Where(a => notFound.Contains(a.Id))
.Select(a => a.IsAllowedForDebug(typeAllowed, ExecutionMode.InUserInterface)).ToList();
string details = debugInfo.ToString(a => " '{0}' because {1}".FormatWith(a.Lite, a.Error), "\r\n");
throw new UnauthorizedAccessException(AuthMessage.NotAuthorizedTo0The1WithId2.NiceToString().FormatWith(
typeAllowed.NiceToString(),
notFound.Length == 1 ? typeof(T).NiceName() : typeof(T).NicePluralName(), notFound.CommaAnd()) + "\r\n" + details);
}
}
}
public static void AssertAllowed(this IEntity ident, TypeAllowedBasic allowed)
{
AssertAllowed(ident, allowed, ExecutionMode.InUserInterface);
}
public static void AssertAllowed(this IEntity ident, TypeAllowedBasic allowed, bool inUserInterface)
{
if (!ident.IsAllowedFor(allowed, inUserInterface))
throw new UnauthorizedAccessException(AuthMessage.NotAuthorizedTo0The1WithId2.NiceToString().FormatWith(allowed.NiceToString().ToLower(), ident.GetType().NiceName(), ident.Id));
}
public static void AssertAllowed(this Lite<IEntity> lite, TypeAllowedBasic allowed)
{
AssertAllowed(lite, allowed, ExecutionMode.InUserInterface);
}
public static void AssertAllowed(this Lite<IEntity> lite, TypeAllowedBasic allowed, bool inUserInterface)
{
if (lite.IdOrNull == null)
AssertAllowed(lite.Entity, allowed, inUserInterface);
if (!lite.IsAllowedFor(allowed, inUserInterface))
throw new UnauthorizedAccessException(AuthMessage.NotAuthorizedTo0The1WithId2.NiceToString().FormatWith(allowed.NiceToString().ToLower(), lite.EntityType.NiceName(), lite.Id));
}
[MethodExpander(typeof(IsAllowedForExpander))]
public static bool IsAllowedFor(this IEntity ident, TypeAllowedBasic allowed)
{
return IsAllowedFor(ident, allowed, ExecutionMode.InUserInterface);
}
[MethodExpander(typeof(IsAllowedForExpander))]
public static bool IsAllowedFor(this IEntity ident, TypeAllowedBasic allowed, bool inUserInterface)
{
return miIsAllowedForEntity.GetInvoker(ident.GetType()).Invoke(ident, allowed, inUserInterface);
}
static GenericInvoker<Func<IEntity, TypeAllowedBasic, bool, bool>> miIsAllowedForEntity
= new((ie, tab, ec) => IsAllowedFor<Entity>((Entity)ie, tab, ec));
[MethodExpander(typeof(IsAllowedForExpander))]
static bool IsAllowedFor<T>(this T entity, TypeAllowedBasic allowed, bool inUserInterface)
where T : Entity
{
if (!AuthLogic.IsEnabled)
return true;
var tac = GetAllowed(entity.GetType());
var min = inUserInterface ? tac.MinUI() : tac.MinDB();
if (allowed <= min)
return true;
var max = inUserInterface ? tac.MaxUI() : tac.MaxDB();
if (max < allowed)
return false;
var inMemoryCodition = IsAllowedInMemory<T>(tac, allowed, inUserInterface);
if (inMemoryCodition != null)
return inMemoryCodition(entity);
using (DisableQueryFilter())
return entity.InDB().WhereIsAllowedFor(allowed, inUserInterface).Any();
}
private static Func<T, bool>? IsAllowedInMemory<T>(TypeAllowedAndConditions tac, TypeAllowedBasic allowed, bool inUserInterface) where T : Entity
{
if (tac.Conditions.Any(c => TypeConditionLogic.GetInMemoryCondition<T>(c.TypeCondition) == null))
return null;
return entity =>
{
foreach (var cond in tac.Conditions.Reverse())
{
var func = TypeConditionLogic.GetInMemoryCondition<T>(cond.TypeCondition)!;
if (func(entity))
return cond.Allowed.Get(inUserInterface) >= allowed;
}
return tac.FallbackOrNone.Get(inUserInterface) >= allowed;
};
}
[MethodExpander(typeof(IsAllowedForExpander))]
public static bool IsAllowedFor(this Lite<IEntity> lite, TypeAllowedBasic allowed)
{
return IsAllowedFor(lite, allowed, ExecutionMode.InUserInterface);
}
[MethodExpander(typeof(IsAllowedForExpander))]
public static bool IsAllowedFor(this Lite<IEntity> lite, TypeAllowedBasic allowed, bool inUserInterface)
{
return miIsAllowedForLite.GetInvoker(lite.EntityType).Invoke(lite, allowed, inUserInterface);
}
static GenericInvoker<Func<Lite<IEntity>, TypeAllowedBasic, bool, bool>> miIsAllowedForLite =
new((l, tab, ec) => IsAllowedFor<Entity>(l, tab, ec));
[MethodExpander(typeof(IsAllowedForExpander))]
static bool IsAllowedFor<T>(this Lite<IEntity> lite, TypeAllowedBasic allowed, bool inUserInterface)
where T : Entity
{
if (!AuthLogic.IsEnabled)
return true;
using (DisableQueryFilter())
return ((Lite<T>)lite).InDB().WhereIsAllowedFor(allowed, inUserInterface).Any();
}
class IsAllowedForExpander : IMethodExpander
{
public Expression Expand(Expression? instance, Expression[] arguments, MethodInfo mi)
{
TypeAllowedBasic allowed = (TypeAllowedBasic)ExpressionEvaluator.Eval(arguments[1])!;
bool inUserInterface = arguments.Length == 3 ? (bool)ExpressionEvaluator.Eval(arguments[2])! : ExecutionMode.InUserInterface;
Expression exp = arguments[0].Type.IsLite() ? Expression.Property(arguments[0], "Entity") : arguments[0];
return IsAllowedExpression(exp, allowed, inUserInterface);
}
}
[MethodExpander(typeof(IsAllowedForDebugExpander))]
public static DebugData IsAllowedForDebug(this IEntity ident, TypeAllowedBasic allowed, bool inUserInterface)
{
return miIsAllowedForDebugEntity.GetInvoker(ident.GetType()).Invoke((Entity)ident, allowed, inUserInterface);
}
[MethodExpander(typeof(IsAllowedForDebugExpander))]
public static string? CanBeModified(this IEntity ident)
{
var taac = TypeAuthLogic.GetAllowed(ident.GetType());
if (taac.Conditions.IsEmpty())
return taac.FallbackOrNone.GetDB() >= TypeAllowedBasic.Write ? null : AuthAdminMessage.CanNotBeModified.NiceToString();
if (ident.IsNew)
return null;
return IsAllowedForDebug(ident, TypeAllowedBasic.Write, false)?.CanBeModified;
}
static GenericInvoker<Func<IEntity, TypeAllowedBasic, bool, DebugData>> miIsAllowedForDebugEntity =
new((ii, tab, ec) => IsAllowedForDebug<Entity>((Entity)ii, tab, ec));
[MethodExpander(typeof(IsAllowedForDebugExpander))]
static DebugData IsAllowedForDebug<T>(this T entity, TypeAllowedBasic allowed, bool inUserInterface)
where T : Entity
{
if (!AuthLogic.IsEnabled)
throw new InvalidOperationException("AuthLogic.IsEnabled is false");
if (entity.IsNew)
throw new InvalidOperationException("The entity {0} is new".FormatWith(entity));
using (DisableQueryFilter())
return entity.InDB().Select(e => e.IsAllowedForDebug(allowed, inUserInterface)).SingleEx();
}
[MethodExpander(typeof(IsAllowedForDebugExpander))]
public static DebugData IsAllowedForDebug(this Lite<IEntity> lite, TypeAllowedBasic allowed, bool inUserInterface)
{
return miIsAllowedForDebugLite.GetInvoker(lite.EntityType).Invoke(lite, allowed, inUserInterface);
}
static GenericInvoker<Func<Lite<IEntity>, TypeAllowedBasic, bool, DebugData>> miIsAllowedForDebugLite =
new((l, tab, ec) => IsAllowedForDebug<Entity>(l, tab, ec));
[MethodExpander(typeof(IsAllowedForDebugExpander))]
static DebugData IsAllowedForDebug<T>(this Lite<IEntity> lite, TypeAllowedBasic allowed, bool inUserInterface)
where T : Entity
{
if (!AuthLogic.IsEnabled)
throw new InvalidOperationException("AuthLogic.IsEnabled is false");
using (DisableQueryFilter())
return ((Lite<T>)lite).InDB().Select(a => a.IsAllowedForDebug(allowed, inUserInterface)).SingleEx();
}
class IsAllowedForDebugExpander : IMethodExpander
{
public Expression Expand(Expression? instance, Expression[] arguments, MethodInfo mi)
{
TypeAllowedBasic allowed = (TypeAllowedBasic)ExpressionEvaluator.Eval(arguments[1])!;
bool inUserInterface = arguments.Length == 3 ? (bool)ExpressionEvaluator.Eval(arguments[2])! : ExecutionMode.InUserInterface;
Expression exp = arguments[0].Type.IsLite() ? Expression.Property(arguments[0], "Entity") : arguments[0];
return IsAllowedExpressionDebug(exp, allowed, inUserInterface);
}
}
static FilterQueryResult<T>? TypeAuthLogic_FilterQuery<T>()
where T : Entity
{
if (queryFilterDisabled.Value)
return null;
if (ExecutionMode.InGlobal || !AuthLogic.IsEnabled)
return null;
var ui = ExecutionMode.InUserInterface;
AssertMinimum<T>(ui);
ParameterExpression e = Expression.Parameter(typeof(T), "e");
var tab = typeof(T) == IsDelete ? TypeAllowedBasic.Write : TypeAllowedBasic.Read;
Expression body = IsAllowedExpression(e, tab, ui);
if (body is ConstantExpression ce)
{
if (((bool)ce.Value!))
return null;
}
Func<T, bool>? func = IsAllowedInMemory<T>(GetAllowed(typeof(T)), tab, ui);
return new FilterQueryResult<T>(Expression.Lambda<Func<T, bool>>(body, e), func);
}
[MethodExpander(typeof(WhereAllowedExpander))]
public static IQueryable<T> WhereAllowed<T>(this IQueryable<T> query)
where T : Entity
{
if (ExecutionMode.InGlobal || !AuthLogic.IsEnabled)
return query;
var ui = ExecutionMode.InUserInterface;
AssertMinimum<T>(ui);
return WhereIsAllowedFor<T>(query, TypeAllowedBasic.Read, ui);
}
private static void AssertMinimum<T>(bool ui) where T : Entity
{
var allowed = GetAllowed(typeof(T));
var max = ui ? allowed.MaxUI() : allowed.MaxDB();
if (max < TypeAllowedBasic.Read)
throw new UnauthorizedAccessException("Type {0} is not authorized{1}{2}".FormatWith(typeof(T).Name,
ui ? " in user interface" : null,
allowed.Conditions.Any() ? " for any condition" : null));
}
[MethodExpander(typeof(WhereIsAllowedForExpander))]
public static IQueryable<T> WhereIsAllowedFor<T>(this IQueryable<T> query, TypeAllowedBasic allowed, bool inUserInterface)
where T : Entity
{
ParameterExpression e = Expression.Parameter(typeof(T), "e");
Expression body = IsAllowedExpression(e, allowed, inUserInterface);
if (body is ConstantExpression ce)
{
if (((bool)ce.Value!))
return query;
}
IQueryable<T> result = query.Where(Expression.Lambda<Func<T, bool>>(body, e));
return result;
}
class WhereAllowedExpander : IMethodExpander
{
public Expression Expand(Expression? instance, Expression[] arguments, MethodInfo mi)
{
return miCallWhereAllowed.GetInvoker(mi.GetGenericArguments()).Invoke(arguments[0]);
}
static GenericInvoker<Func<Expression, Expression>> miCallWhereAllowed = new(exp => CallWhereAllowed<TypeEntity>(exp));
static Expression CallWhereAllowed<T>(Expression expression)
where T : Entity
{
IQueryable<T> query = new Query<T>(DbQueryProvider.Single, expression);
IQueryable<T> result = WhereAllowed(query);
return result.Expression;
}
}
class WhereIsAllowedForExpander : IMethodExpander
{
public Expression Expand(Expression? instance, Expression[] arguments, MethodInfo mi)
{
TypeAllowedBasic allowed = (TypeAllowedBasic)ExpressionEvaluator.Eval(arguments[1])!;
bool inUserInterface = (bool)ExpressionEvaluator.Eval(arguments[2])!;
return miCallWhereIsAllowedFor.GetInvoker(mi.GetGenericArguments())(arguments[0], allowed, inUserInterface);
}
static GenericInvoker<Func<Expression, TypeAllowedBasic, bool, Expression>> miCallWhereIsAllowedFor =
new((ex, tab, ui) => CallWhereIsAllowedFor<TypeEntity>(ex, tab, ui));
static Expression CallWhereIsAllowedFor<T>(Expression expression, TypeAllowedBasic allowed, bool inUserInterface)
where T : Entity
{
IQueryable<T> query = new Query<T>(DbQueryProvider.Single, expression);
IQueryable<T> result = WhereIsAllowedFor(query, allowed, inUserInterface);
return result.Expression;
}
}
public static Expression IsAllowedExpression(Expression entity, TypeAllowedBasic requested, bool inUserInterface)
{
Type type = entity.Type;
TypeAllowedAndConditions tac = GetAllowed(type);
Expression baseValue = Expression.Constant(tac.FallbackOrNone.Get(inUserInterface) >= requested);
var expression = tac.Conditions.Aggregate(baseValue, (acum, tacRule) =>
{
var lambda = TypeConditionLogic.GetCondition(type, tacRule.TypeCondition);
var exp = (Expression)Expression.Invoke(lambda, entity);
if (tacRule.Allowed.Get(inUserInterface) >= requested)
return Expression.Or(exp, acum);
else
return Expression.And(Expression.Not(exp), acum);
});
var cleaned = DbQueryProvider.Clean(expression, false, null)!;
var orsSimplified = AndOrSimplifierVisitor.SimplifyOrs(cleaned);
return orsSimplified;
}
static ConstructorInfo ciDebugData = ReflectionTools.GetConstuctorInfo(() => new DebugData(null!, TypeAllowedBasic.Write, true, TypeAllowed.Write, null!));
static ConstructorInfo ciGroupDebugData = ReflectionTools.GetConstuctorInfo(() => new ConditionDebugData(null!, true, TypeAllowed.Write));
static MethodInfo miToLite = ReflectionTools.GetMethodInfo((Entity a) => a.ToLite()).GetGenericMethodDefinition();
internal static Expression IsAllowedExpressionDebug(Expression entity, TypeAllowedBasic requested, bool inUserInterface)
{
Type type = entity.Type;
TypeAllowedAndConditions tac = GetAllowed(type);
Expression baseValue = Expression.Constant(tac.FallbackOrNone.Get(inUserInterface) >= requested);
var list = (from line in tac.Conditions
select Expression.New(ciGroupDebugData, Expression.Constant(line.TypeCondition, typeof(TypeConditionSymbol)),
Expression.Invoke(TypeConditionLogic.GetCondition(type, line.TypeCondition), entity),
Expression.Constant(line.Allowed))).ToArray();
Expression newList = Expression.ListInit(Expression.New(typeof(List<ConditionDebugData>)), list);
Expression liteEntity = Expression.Call(null, miToLite.MakeGenericMethod(entity.Type), entity);
return Expression.New(ciDebugData, liteEntity,
Expression.Constant(requested),
Expression.Constant(inUserInterface),
Expression.Constant(tac.Fallback),
newList);
}
public class DebugData
{
public DebugData(Lite<IEntity> lite, TypeAllowedBasic requested, bool userInterface, TypeAllowed fallback, List<ConditionDebugData> groups)
{
this.Lite = lite;
this.Requested = requested;
this.Fallback = fallback;
this.UserInterface = userInterface;
this.Conditions = groups;
}
public Lite<IEntity> Lite { get; private set; }
public TypeAllowedBasic Requested { get; private set; }
public TypeAllowed Fallback { get; private set; }
public bool UserInterface { get; private set; }
public List<ConditionDebugData> Conditions { get; private set; }
public bool IsAllowed
{
get
{
foreach (var item in Conditions.AsEnumerable().Reverse())
{
if (item.InGroup)
return Requested <= item.Allowed.Get(UserInterface);
}
return Requested <= Fallback.Get(UserInterface);
}
}
public string? Error
{
get
{
foreach (var cond in Conditions.AsEnumerable().Reverse())
{
if (cond.InGroup)
return Requested <= cond.Allowed.Get(UserInterface) ? null :
"is a {0} that belongs to condition {1} that is {2} (less than {3})".FormatWith(Lite.EntityType.TypeName(), cond.TypeCondition, cond.Allowed.Get(UserInterface), Requested);
}
return Requested <= Fallback.Get(UserInterface) ? null :
"is a {0} but does not belong to any condition and the base value is {1} (less than {2})".FormatWith(Lite.EntityType.TypeName(), Fallback.Get(UserInterface), Requested);
}
}
public string? CanBeModified
{
get
{
foreach (var cond in Conditions.AsEnumerable().Reverse())
{
if (cond.InGroup)
return Requested <= cond.Allowed.Get(UserInterface) ? null :
AuthAdminMessage.CanNotBeModifiedBecauseIsA0.NiceToString(cond.TypeCondition.NiceToString());
}
return Requested <= Fallback.Get(UserInterface) ? null :
AuthAdminMessage.CanNotBeModifiedBecauseIsNotA0.NiceToString(Conditions.AsEnumerable().Reverse());
}
}
}
public class ConditionDebugData
{
public TypeConditionSymbol TypeCondition { get; private set; }
public bool InGroup { get; private set; }
public TypeAllowed Allowed { get; private set; }
internal ConditionDebugData(TypeConditionSymbol typeCondition, bool inGroup, TypeAllowed allowed)
{
this.TypeCondition = typeCondition;
this.InGroup = inGroup;
this.Allowed = allowed;
}
}
public static DynamicQueryCore<T> ToDynamicDisableAuth<T>(this IQueryable<T> query, bool disableQueryFilter = false, bool authDisable = true)
{
return new AutoDynamicQueryNoFilterCore<T>(query)
{
DisableQueryFilter = disableQueryFilter,
AuthDisable = authDisable,
};
}
internal class AutoDynamicQueryNoFilterCore<T> : AutoDynamicQueryCore<T>
{
public bool DisableQueryFilter { get; internal set; }
public bool AuthDisable { get; internal set; }
public AutoDynamicQueryNoFilterCore(IQueryable<T> query)
: base(query)
{ }
public override async Task<ResultTable> ExecuteQueryAsync(QueryRequest request, CancellationToken token)
{
using (this.AuthDisable ? AuthLogic.Disable() : null)
using (this.DisableQueryFilter ? TypeAuthLogic.DisableQueryFilter() : null)
{
return await base.ExecuteQueryAsync(request, token);
}
}
public override async Task<Lite<Entity>?> ExecuteUniqueEntityAsync(UniqueEntityRequest request, CancellationToken token)
{
using (this.AuthDisable ? AuthLogic.Disable() : null)
using (this.DisableQueryFilter ? TypeAuthLogic.DisableQueryFilter() : null)
{
return await base.ExecuteUniqueEntityAsync(request, token);
}
}
public override async Task<object?> ExecuteQueryValueAsync(QueryValueRequest request, CancellationToken token)
{
using (this.AuthDisable ? AuthLogic.Disable() : null)
using (this.DisableQueryFilter ? TypeAuthLogic.DisableQueryFilter() : null)
{
return await base.ExecuteQueryValueAsync(request, token);
}
}
}
public static RuleTypeEntity ToRuleType(this TypeAllowedAndConditions allowed, Lite<RoleEntity> role, TypeEntity resource)
{
return new RuleTypeEntity
{
Role = role,
Resource = resource,
Allowed = allowed.Fallback!.Value,
Conditions = allowed.Conditions.Select(a => new RuleTypeConditionEmbedded
{
Allowed = a.Allowed,
Condition = a.TypeCondition
}).ToMList()
};
}
public static TypeAllowedAndConditions ToTypeAllowedAndConditions(this RuleTypeEntity rule)
{
return new TypeAllowedAndConditions(rule.Allowed,
rule.Conditions.Select(c => new TypeConditionRuleEmbedded(c.Condition, c.Allowed)));
}
static SqlPreCommand? Schema_Synchronizing(Replacements rep)
{
var conds = (from rt in Database.Query<RuleTypeEntity>()
from c in rt.Conditions
select new { rt.Resource, c.Condition, rt.Role }).ToList();
var errors = conds.GroupBy(a => new { a.Resource, a.Condition }, a => a.Role)
.Where(gr =>
{
if (gr.Key.Condition!.FieldInfo == null) /*CSBUG*/
{
var replacedName = rep.TryGetC(typeof(TypeConditionSymbol).Name)?.TryGetC(gr.Key.Condition.Key);
if (replacedName == null)
return false; // Other Syncronizer will do it
return !TypeConditionLogic.ConditionsFor(gr.Key.Resource!.ToType()).Any(a => a.Key == replacedName);
}
return !TypeConditionLogic.IsDefined(gr.Key.Resource!.ToType(), gr.Key.Condition);
})
.ToList();
using (rep.WithReplacedDatabaseName())
return errors.Select(a =>
{
return Administrator.UnsafeDeletePreCommandMList((RuleTypeEntity rt) => rt.Conditions, Database.MListQuery((RuleTypeEntity rt) => rt.Conditions)
.Where(mle => mle.Element.Condition.Is(a.Key.Condition) && mle.Parent.Resource.Is(a.Key.Resource)))!
.AddComment("TypeCondition {0} not defined for {1} (roles {2})".FormatWith(a.Key.Condition, a.Key.Resource, a.ToString(", ")));
}).Combine(Spacing.Double);
}
}
public static class AndOrSimplifierVisitor
{
class HashSetComparer<T> : IEqualityComparer<HashSet<T>>
{
public bool Equals(HashSet<T>? x, HashSet<T>? y)
{
return x != null && y != null && x.SetEquals(y);
}
public int GetHashCode([DisallowNull] HashSet<T> obj)
{
return obj.Count ;
}
}
static IEqualityComparer<Expression> Comparer = ExpressionComparer.GetComparer<Expression>(false);
static IEqualityComparer<HashSet<Expression>> HSetComparer = new HashSetComparer<Expression>();
public static Expression SimplifyOrs(Expression expr)
{
if (expr is BinaryExpression b && (b.NodeType == ExpressionType.Or || b.NodeType == ExpressionType.OrElse))
{
var orGroups = OrAndList(b);
var newOrGroups = orGroups.Where(og => !orGroups.Any(og2 => og2 != og && og2.IsMoreSimpleAndGeneralThan(og))).ToList();
return newOrGroups.Select(andGroup => andGroup.Aggregate(Expression.AndAlso)).Aggregate(Expression.OrElse);
}
return expr;
}
static HashSet<HashSet<Expression>> OrAndList(Expression expression)
{
if (expression is BinaryExpression b && (b.NodeType == ExpressionType.Or || b.NodeType == ExpressionType.OrElse))
{
return OrAndList(b.Left).Concat(OrAndList(b.Right)).ToHashSet(HSetComparer);
}
else
{
var ands = AndList(expression);
return new HashSet<HashSet<Expression>>(HSetComparer) { ands };
}
}
static HashSet<Expression> AndList(Expression expression)
{
if (expression is BinaryExpression b && (b.NodeType == ExpressionType.And || b.NodeType == ExpressionType.AndAlso))
return AndList(b.Left).Concat(AndList(b.Right)).ToHashSet(Comparer);
else
return new HashSet<Expression>(Comparer){ expression };
}
static bool IsMoreSimpleAndGeneralThan(this HashSet<Expression> simple, HashSet<Expression> complex)
{
return simple.All(a => complex.Contains(a));
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
/// <summary>
/// Contains various static functions and methods for parsing and validating:
/// NCName (not namespace-aware, no colons allowed)
/// QName (prefix:local-name)
/// </summary>
internal static class ValidateNames
{
internal enum Flags
{
NCNames = 0x1, // Validate that each non-empty prefix and localName is a valid NCName
CheckLocalName = 0x2, // Validate the local-name
CheckPrefixMapping = 0x4, // Validate the prefix --> namespace mapping
All = 0x7,
AllExceptNCNames = 0x6,
AllExceptPrefixMapping = 0x3,
};
static XmlCharType xmlCharType = XmlCharType.Instance;
//-----------------------------------------------
// Nmtoken parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an Nmtoken (see the XML spec production [7] && XML Namespaces spec).
/// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached.
/// Returns the number of valid Nmtoken chars that were parsed.
/// </summary>
internal static unsafe int ParseNmtoken(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Keep parsing until the end of string or an invalid NCName character is reached
int i = offset;
while (i < s.Length)
{
if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0)
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
break;
}
}
return i - offset;
}
//-----------------------------------------------
// Nmtoken parsing (no XML namespaces support)
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an Nmtoken (see the XML spec production [7]) without taking
/// into account the XML Namespaces spec. What it means is that the ':' character is allowed at any
/// position and any number of times in the token.
/// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached.
/// Returns the number of valid Nmtoken chars that were parsed.
/// </summary>
internal static unsafe int ParseNmtokenNoNamespaces(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Keep parsing until the end of string or an invalid Name character is reached
int i = offset;
while (i < s.Length)
{
if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0 || s[i] == ':')
{ // if (xmlCharType.IsNameSingleChar(s[i])) {
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
break;
}
}
return i - offset;
}
// helper methods
internal static bool IsNmtokenNoNamespaces(string s)
{
int endPos = ParseNmtokenNoNamespaces(s, 0);
return endPos > 0 && endPos == s.Length;
}
//-----------------------------------------------
// Name parsing (no XML namespaces support)
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as a Name without taking into account the XML Namespaces spec.
/// What it means is that the ':' character does not delimiter prefix and local name, but it is a regular
/// name character, which is allowed to appear at any position and any number of times in the name.
/// Quits parsing when an invalid Name char is reached or the end of string is reached.
/// Returns the number of valid Name chars that were parsed.
/// </summary>
internal static unsafe int ParseNameNoNamespaces(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Quit if the first character is not a valid NCName starting character
int i = offset;
if (i < s.Length)
{
if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCStartNameSC) != 0 || s[i] == ':')
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
return 0; // no valid StartNCName char
}
// Keep parsing until the end of string or an invalid NCName character is reached
while (i < s.Length)
{
if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0 || s[i] == ':')
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
break;
}
}
}
return i - offset;
}
// helper methods
internal static bool IsNameNoNamespaces(string s)
{
int endPos = ParseNameNoNamespaces(s, 0);
return endPos > 0 && endPos == s.Length;
}
//-----------------------------------------------
// NCName parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an NCName (see the XML Namespace spec).
/// Quits parsing when an invalid NCName char is reached or the end of string is reached.
/// Returns the number of valid NCName chars that were parsed.
/// </summary>
internal static unsafe int ParseNCName(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Quit if the first character is not a valid NCName starting character
int i = offset;
if (i < s.Length)
{
if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCStartNameSC) != 0)
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
return 0; // no valid StartNCName char
}
// Keep parsing until the end of string or an invalid NCName character is reached
while (i < s.Length)
{
if ((xmlCharType.charProperties[s[i]] & XmlCharType.fNCNameSC) != 0)
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
break;
}
}
}
return i - offset;
}
internal static int ParseNCName(string s)
{
return ParseNCName(s, 0);
}
//-----------------------------------------------
// QName parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as a QName (see the XML Namespace spec).
/// Quits parsing when an invalid QName char is reached or the end of string is reached.
/// Returns the number of valid QName chars that were parsed.
/// Sets colonOffset to the offset of a colon character if it exists, or 0 otherwise.
/// </summary>
internal static int ParseQName(string s, int offset, out int colonOffset)
{
// Assume no colon
colonOffset = 0;
// Parse NCName (may be prefix, may be local name)
int len = ParseNCName(s, offset);
if (len != 0)
{
// Non-empty NCName, so look for colon if there are any characters left
offset += len;
if (offset < s.Length && s[offset] == ':')
{
// First NCName was prefix, so look for local name part
int lenLocal = ParseNCName(s, offset + 1);
if (lenLocal != 0)
{
// Local name part found, so increase total QName length (add 1 for colon)
colonOffset = offset;
len += lenLocal + 1;
}
}
}
return len;
}
/// <summary>
/// Calls parseQName and throws exception if the resulting name is not a valid QName.
/// Returns the prefix and local name parts.
/// </summary>
internal static void ParseQNameThrow(string s, out string prefix, out string localName)
{
int colonOffset;
int len = ParseQName(s, 0, out colonOffset);
if (len == 0 || len != s.Length)
{
// If the string is not a valid QName, then throw
ThrowInvalidName(s, 0, len);
}
if (colonOffset != 0)
{
prefix = s.Substring(0, colonOffset);
localName = s.Substring(colonOffset + 1);
}
else
{
prefix = "";
localName = s;
}
}
/// <summary>
/// Throws an invalid name exception.
/// </summary>
/// <param name="s">String that was parsed.</param>
/// <param name="offsetStartChar">Offset in string where parsing began.</param>
/// <param name="offsetBadChar">Offset in string where parsing failed.</param>
internal static void ThrowInvalidName(string s, int offsetStartChar, int offsetBadChar)
{
// If the name is empty, throw an exception
if (offsetStartChar >= s.Length)
throw new XmlException(SR.Xml_EmptyName);
Debug.Assert(offsetBadChar < s.Length);
if (xmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !XmlCharType.Instance.IsStartNCNameSingleChar(s[offsetBadChar]))
{
// The error character is a valid name character, but is not a valid start name character
throw new XmlException(SR.Format(SR.Xml_BadStartNameChar, XmlExceptionHelper.BuildCharExceptionArgs(s, offsetBadChar)));
}
else
{
// The error character is an invalid name character
throw new XmlException(SR.Format(SR.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(s, offsetBadChar)));
}
}
/// <summary>
/// Split a QualifiedName into prefix and localname, w/o any checking.
/// (Used for XmlReader/XPathNavigator MoveTo(name) methods)
/// </summary>
internal static void SplitQName(string name, out string prefix, out string lname)
{
int colonPos = name.IndexOf(':');
if (-1 == colonPos)
{
prefix = string.Empty;
lname = name;
}
else if (0 == colonPos || (name.Length - 1) == colonPos)
{
throw new ArgumentException(SR.Format(SR.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(':', '\0')), "name");
}
else
{
prefix = name.Substring(0, colonPos);
colonPos++; // move after colon
lname = name.Substring(colonPos, name.Length - colonPos);
}
}
}
internal class XmlExceptionHelper
{
internal static string[] BuildCharExceptionArgs(string data, int invCharIndex)
{
return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < data.Length ? data[invCharIndex + 1] : '\0');
}
internal static string[] BuildCharExceptionArgs(char[] data, int invCharIndex)
{
return BuildCharExceptionArgs(data, data.Length, invCharIndex);
}
internal static string[] BuildCharExceptionArgs(char[] data, int length, int invCharIndex)
{
Debug.Assert(invCharIndex < data.Length);
Debug.Assert(invCharIndex < length);
Debug.Assert(length <= data.Length);
return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < length ? data[invCharIndex + 1] : '\0');
}
internal static string[] BuildCharExceptionArgs(char invChar, char nextChar)
{
string[] aStringList = new string[2];
// for surrogate characters include both high and low char in the message so that a full character is displayed
if (XmlCharType.IsHighSurrogate(invChar) && nextChar != 0)
{
int combinedChar = XmlCharType.CombineSurrogateChar(nextChar, invChar);
aStringList[0] = new string(new char[] { invChar, nextChar });
aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", combinedChar);
}
else
{
// don't include 0 character in the string - in means eof-of-string in native code, where this may bubble up to
if ((int)invChar == 0)
{
aStringList[0] = ".";
}
else
{
aStringList[0] = Convert.ToString(invChar, CultureInfo.InvariantCulture);
}
aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", (int)invChar);
}
return aStringList;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Timers;
using log4net;
using Timer = System.Timers.Timer;
namespace NetGore.IO
{
/// <summary>
/// Manages the settings of a collection of <see cref="IPersistable"/> objects by saving the state to file for
/// all managed objects, along with loading the previous state for objects when they are added to the manager.
/// </summary>
public class ObjectStatePersister : IDisposable
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
const string _countValueName = "Count";
/// <summary>
/// The initial auto-save rate.
/// </summary>
const int _initialAutoSaveRate = 60000;
const string _itemNodeName = "Item";
const string _itemsNodeName = "Items";
const string _keyValueName = "Key";
const string _valueNodeName = "Values";
/// <summary>
/// The <see cref="StringComparer"/> to use for the created dictionaries.
/// </summary>
static readonly StringComparer _keyStringComparer = StringComparer.OrdinalIgnoreCase;
/// <summary>
/// File path being used.
/// </summary>
readonly string _filePath;
/// <summary>
/// Contains the collection of loaded settings that have not yet been loaded back. Values in here wait until
/// an <see cref="IPersistable"/>s is added through Add() that has the same key as in this. When a match is found,
/// the item is removed from this collection. Therefore, if this collection is empty, all settings have been restored.
/// </summary>
readonly Dictionary<string, IValueReader> _loadedNodeItems;
/// <summary>
/// Dictionary of <see cref="IPersistable"/> objects being tracked, indexed by their unique identifier.
/// </summary>
readonly Dictionary<string, IPersistable> _objs = new Dictionary<string, IPersistable>(_keyStringComparer);
readonly string _rootNode;
readonly object _saveLock = new object();
Timer _autoSaveTimer;
bool _disposed = false;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectStatePersister"/> class.
/// </summary>
/// <param name="rootNode">Name of the root node. Used to ensure the correct file is loaded when
/// loading settings. Not required to be unique, but recommended.</param>
/// <param name="filePath">Primary file path to use, and first place to check for settings.</param>
public ObjectStatePersister(string rootNode, string filePath) : this(rootNode, filePath, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObjectStatePersister"/> class.
/// </summary>
/// <param name="rootNode">Name of the root node. Used to ensure the correct file is loaded when
/// loading settings. Not required to be unique, but recommended.</param>
/// <param name="filePath">Primary file path to use, and first place to check for settings.</param>
/// <param name="secondaryPath">Secondary path to check for settings from. The FilePath will still be
/// <paramref name="filePath"/>, but the settings can be loaded from somewhere else, like a default
/// settings file.</param>
public ObjectStatePersister(string rootNode, string filePath, string secondaryPath)
: this(rootNode, filePath, new string[] { secondaryPath })
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObjectStatePersister"/> class.
/// </summary>
/// <param name="rootNode">Name of the root node. Used to ensure the correct file is loaded when
/// loading settings. Not required to be unique, but recommended.</param>
/// <param name="filePath">Primary file path to use, and first place to check for settings.</param>
/// <param name="secondaryPaths">Secondary paths to check for settings from. The FilePath will still be
/// <paramref name="filePath"/>, but the settings can be loaded from somewhere else, like a default
/// settings file. The first path to contain a file, even if not a valid settings file, is used to
/// load the settings from.</param>
public ObjectStatePersister(string rootNode, string filePath, IEnumerable<string> secondaryPaths)
{
_rootNode = rootNode;
_filePath = filePath;
// Try to load from the primary path, then the secondary paths if the primary fails
var loadedItems = LoadSettings(filePath);
if (loadedItems == null)
{
foreach (var secondaryPath in secondaryPaths.Where(x => !string.IsNullOrEmpty(x)))
{
loadedItems = LoadSettings(secondaryPath);
if (loadedItems != null)
break;
}
}
_loadedNodeItems = loadedItems ?? new Dictionary<string, IValueReader>(_keyStringComparer);
// Set up the auto-save timer
AutoSaveRate = _initialAutoSaveRate;
}
/// <summary>
/// Gets or sets the rate in milliseconds at which the <see cref="ObjectStatePersister"/> is automatically saved. If the
/// value is less than or equal to 0, auto-saving will be disabled.
/// </summary>
public int AutoSaveRate
{
get { return _autoSaveTimer == null ? 0 : (int)_autoSaveTimer.Interval; }
set
{
if (value > 0)
{
// Check if the value is already set
if (_autoSaveTimer != null && value == (int)_autoSaveTimer.Interval)
return;
// Positive value and not what we already have, so check if we need to create the timer
if (_autoSaveTimer == null)
{
_autoSaveTimer = new Timer { AutoReset = false };
_autoSaveTimer.Elapsed += AutoSaveTimer_Elapsed;
_autoSaveTimer.Start();
}
_autoSaveTimer.Interval = value;
}
else
{
// Check if the timer is already null
if (_autoSaveTimer == null)
return;
// Dispose of the timer
_autoSaveTimer.Dispose();
_autoSaveTimer = null;
}
}
}
/// <summary>
/// Gets or sets the <see cref="GenericValueIOFormat"/> to use for when an instance of this class
/// writes itself out to a new <see cref="GenericValueWriter"/>. If null, the format to use
/// will be inherited from <see cref="GenericValueWriter.DefaultFormat"/>.
/// Default value is null.
/// </summary>
public static GenericValueIOFormat? EncodingFormat { get; set; }
/// <summary>
/// Gets the file path used to load and save the settings.
/// </summary>
public string FilePath
{
get { return _filePath; }
}
/// <summary>
/// Gets if this GUISettings has been disposed of.
/// </summary>
public bool IsDisposed
{
get { return _disposed; }
}
/// <summary>
/// Gets the name of the root node used for Xml file. Only an Xml file that contains the same
/// root node name as this will be able to be loaded by this <see cref="ObjectStatePersister"/>.
/// </summary>
public string RootNode
{
get { return _rootNode; }
}
/// <summary>
/// Adds an object to be tracked by this <see cref="ObjectStatePersister"/> and loads the previous settings
/// for the object if possible.
/// </summary>
/// <param name="objs">The persistable object and unique key pairs.</param>
/// <exception cref="ArgumentException">An object with the key provided by any of the <paramref name="objs"/>
/// already exists in this collection.</exception>
public void Add(IEnumerable<KeyValuePair<string, IPersistable>> objs)
{
foreach (var obj in objs)
{
Add(obj.Key, obj.Value);
}
}
/// <summary>
/// Adds an object to be tracked by this <see cref="ObjectStatePersister"/> and loads the previous settings
/// for the object if possible.
/// </summary>
/// <param name="obj">The persistable object and unique key pair.</param>
/// <exception cref="ArgumentException">An object with the key provided by the <paramref name="obj"/> already exists
/// in this collection.</exception>
public void Add(KeyValuePair<string, IPersistable> obj)
{
Add(obj.Key, obj.Value);
}
/// <summary>
/// Adds an object to be tracked by this <see cref="ObjectStatePersister"/> and loads the previous settings
/// for the object if possible.
/// </summary>
/// <param name="key">Unique identifier of the <see cref="IPersistable"/> object.</param>
/// <param name="obj"><see cref="IPersistable"/> object to load and save the settings for.</param>
/// <exception cref="ArgumentException">An object with the given <paramref name="key"/> already exists
/// in this collection.</exception>
public void Add(string key, IPersistable obj)
{
// Add to the gui items to track
_objs.Add(key, obj);
// Check if the settings need to be restored
IValueReader valueReader;
if (_loadedNodeItems.TryGetValue(key, out valueReader))
{
try
{
obj.ReadState(valueReader);
}
catch (Exception ex)
{
// If we fail to read the state, just absorb the exception while printing an error
const string errmsg = "Failed to load settings for object `{0}` with key `{1}`: {2}";
var err = string.Format(errmsg, obj, key, ex);
log.Error(err);
Debug.Fail(err);
}
_loadedNodeItems.Remove(key);
}
}
/// <summary>
/// Asynchronously saves the settings for all the tracked <see cref="IPersistable"/> objects.
/// </summary>
public void AsyncSave()
{
ThreadPool.QueueUserWorkItem(AsyncSaveCallback, this);
}
/// <summary>
/// Callback for saving using the thread pool.
/// </summary>
/// <param name="sender">The <see cref="ObjectStatePersister"/> the request came from.</param>
static void AsyncSaveCallback(object sender)
{
((ObjectStatePersister)sender).Save();
}
/// <summary>
/// Handles the Elapsed event of the <see cref="_autoSaveTimer"/> control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param>
void AutoSaveTimer_Elapsed(object sender, ElapsedEventArgs e)
{
// Ensure the timer is stopped so we don't try saving multiple times at once
_autoSaveTimer.Stop();
// Perform the save
Save();
// Start the timer back up
_autoSaveTimer.AutoReset = false;
_autoSaveTimer.Start();
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="ObjectStatePersister"/> is reclaimed by garbage collection.
/// </summary>
~ObjectStatePersister()
{
Dispose();
}
/// <summary>
/// Loads the existing settings into memory.
/// </summary>
/// <param name="path">Path of the file to load the settings from.</param>
/// <returns>A Dictionary of all the items loaded, if any, or null if there was an error in loading.</returns>
Dictionary<string, IValueReader> LoadSettings(string path)
{
if (string.IsNullOrEmpty(path) || !File.Exists(path))
return null;
var fi = new FileInfo(path);
if (fi.Length < 1)
return null;
var nodeReaders = new Dictionary<string, IValueReader>(_keyStringComparer);
try
{
var reader = GenericValueReader.CreateFromFile(path, _rootNode);
reader = reader.ReadNode(_itemsNodeName);
var count = reader.ReadInt(_countValueName);
for (var i = 0; i < count; i++)
{
var nodeReader = reader.ReadNode(_itemNodeName + i);
var keyName = nodeReader.ReadString(_keyValueName);
var valueReader = nodeReader.ReadNode(_valueNodeName);
nodeReaders.Add(keyName, valueReader);
}
}
catch (Exception ex)
{
const string errmsg = "Failed to load settings from `{0}`. Exception: {1}";
if (log.IsErrorEnabled)
log.Error(string.Format(errmsg, path, ex));
Debug.Fail(string.Format(errmsg, path, ex));
return null;
}
return nodeReaders;
}
/// <summary>
/// Saves the settings for all the tracked <see cref="IPersistable"/> objects.
/// </summary>
public void Save()
{
var objs = _objs.ToArray();
// Lock to ensure we never try to save from multiple threads at once
lock (_saveLock)
{
using (var w = GenericValueWriter.Create(_filePath, _rootNode, EncodingFormat))
{
w.WriteStartNode(_itemsNodeName);
{
w.Write(_countValueName, objs.Length);
for (var i = 0; i < objs.Length; i++)
{
w.WriteStartNode(_itemNodeName + i);
{
var obj = objs[i];
w.Write(_keyValueName, obj.Key);
w.WriteStartNode(_valueNodeName);
{
obj.Value.WriteState(w);
}
w.WriteEndNode(_valueNodeName);
}
w.WriteEndNode(_itemNodeName + i);
}
}
w.WriteEndNode(_itemsNodeName);
}
}
}
#region IDisposable Members
/// <summary>
/// Disposes the GUISettings and flushes out the stored settings.
/// </summary>
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
GC.SuppressFinalize(this);
Save();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using TrueCraft.API;
using TrueCraft.API.World;
using TrueCraft.API.Logic;
using fNbt;
using System.Collections;
namespace TrueCraft.Core.World
{
public class World : IDisposable, IWorld, IEnumerable<IChunk>
{
public static readonly int Height = 128;
public string Name { get; set; }
public int Seed { get; set; }
private Coordinates3D? _SpawnPoint;
public Coordinates3D SpawnPoint
{
get
{
if (_SpawnPoint == null)
_SpawnPoint = ChunkProvider.GetSpawn(this);
return _SpawnPoint.Value;
}
set
{
_SpawnPoint = value;
}
}
public string BaseDirectory { get; internal set; }
public IDictionary<Coordinates2D, IRegion> Regions { get; set; }
public IBiomeMap BiomeDiagram { get; set; }
public IChunkProvider ChunkProvider { get; set; }
public IBlockRepository BlockRepository { get; set; }
public DateTime BaseTime { get; set; }
public long Time
{
get
{
return (long)((DateTime.UtcNow - BaseTime).TotalSeconds * 20) % 24000;
}
set
{
BaseTime = DateTime.UtcNow.AddSeconds(-value / 20);
}
}
public event EventHandler<BlockChangeEventArgs> BlockChanged;
public event EventHandler<ChunkLoadedEventArgs> ChunkGenerated;
public event EventHandler<ChunkLoadedEventArgs> ChunkLoaded;
public World()
{
Regions = new Dictionary<Coordinates2D, IRegion>();
BaseTime = DateTime.UtcNow;
}
public World(string name) : this()
{
Name = name;
Seed = new Random().Next();
BiomeDiagram = new BiomeMap(Seed);
}
public World(string name, IChunkProvider chunkProvider) : this(name)
{
ChunkProvider = chunkProvider;
}
public World(string name, int seed, IChunkProvider chunkProvider) : this(name, chunkProvider)
{
Seed = seed;
BiomeDiagram = new BiomeMap(Seed);
}
public static World LoadWorld(string baseDirectory)
{
if (!Directory.Exists(baseDirectory))
throw new DirectoryNotFoundException();
var world = new World(Path.GetFileName(baseDirectory));
world.BaseDirectory = baseDirectory;
if (File.Exists(Path.Combine(baseDirectory, "manifest.nbt")))
{
var file = new NbtFile(Path.Combine(baseDirectory, "manifest.nbt"));
world.SpawnPoint = new Coordinates3D(file.RootTag["SpawnPoint"]["X"].IntValue,
file.RootTag["SpawnPoint"]["Y"].IntValue,
file.RootTag["SpawnPoint"]["Z"].IntValue);
world.Seed = file.RootTag["Seed"].IntValue;
var providerName = file.RootTag["ChunkProvider"].StringValue;
var provider = (IChunkProvider)Activator.CreateInstance(Type.GetType(providerName), world);
if (file.RootTag.Contains("Name"))
world.Name = file.RootTag["Name"].StringValue;
world.ChunkProvider = provider;
}
return world;
}
/// <summary>
/// Finds a chunk that contains the specified block coordinates.
/// </summary>
public IChunk FindChunk(Coordinates3D coordinates, bool generate = true)
{
IChunk chunk;
FindBlockPosition(coordinates, out chunk, generate);
return chunk;
}
public IChunk GetChunk(Coordinates2D coordinates, bool generate = true)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ), generate);
if (region == null)
return null;
return region.GetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32), generate);
}
public void GenerateChunk(Coordinates2D coordinates)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ));
region.GenerateChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32));
}
public void SetChunk(Coordinates2D coordinates, Chunk chunk)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ));
lock (region)
{
chunk.IsModified = true;
region.SetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32), chunk);
}
}
public void UnloadRegion(Coordinates2D coordinates)
{
lock (Regions)
{
Regions[coordinates].Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates)));
Regions.Remove(coordinates);
}
}
public void UnloadChunk(Coordinates2D coordinates)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var regionPosition = new Coordinates2D(regionX, regionZ);
if (!Regions.ContainsKey(regionPosition))
throw new ArgumentOutOfRangeException("coordinates");
Regions[regionPosition].UnloadChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32));
}
public byte GetBlockID(Coordinates3D coordinates)
{
IChunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetBlockID(coordinates);
}
public byte GetMetadata(Coordinates3D coordinates)
{
IChunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetMetadata(coordinates);
}
public byte GetSkyLight(Coordinates3D coordinates)
{
IChunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetSkyLight(coordinates);
}
public byte GetBlockLight(Coordinates3D coordinates)
{
IChunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetBlockLight(coordinates);
}
public NbtCompound GetTileEntity(Coordinates3D coordinates)
{
IChunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetTileEntity(coordinates);
}
public BlockDescriptor GetBlockData(Coordinates3D coordinates)
{
IChunk chunk;
var adjustedCoordinates = FindBlockPosition(coordinates, out chunk);
return GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates);
}
public void SetBlockData(Coordinates3D coordinates, BlockDescriptor descriptor)
{
IChunk chunk;
var adjustedCoordinates = FindBlockPosition(coordinates, out chunk);
var old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates);
chunk.SetBlockID(adjustedCoordinates, descriptor.ID);
chunk.SetMetadata(adjustedCoordinates, descriptor.Metadata);
if (BlockChanged != null)
BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates)));
}
private BlockDescriptor GetBlockDataFromChunk(Coordinates3D adjustedCoordinates, IChunk chunk, Coordinates3D coordinates)
{
return new BlockDescriptor
{
ID = chunk.GetBlockID(adjustedCoordinates),
Metadata = chunk.GetMetadata(adjustedCoordinates),
BlockLight = chunk.GetBlockLight(adjustedCoordinates),
SkyLight = chunk.GetSkyLight(adjustedCoordinates),
Coordinates = coordinates
};
}
public void SetBlockID(Coordinates3D coordinates, byte value)
{
IChunk chunk;
var adjustedCoordinates = FindBlockPosition(coordinates, out chunk);
BlockDescriptor old = new BlockDescriptor();
if (BlockChanged != null)
old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates);
chunk.SetBlockID(adjustedCoordinates, value);
if (BlockChanged != null)
BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates)));
}
public void SetMetadata(Coordinates3D coordinates, byte value)
{
IChunk chunk;
var adjustedCoordinates = FindBlockPosition(coordinates, out chunk);
BlockDescriptor old = new BlockDescriptor();
if (BlockChanged != null)
old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates);
chunk.SetMetadata(adjustedCoordinates, value);
if (BlockChanged != null)
BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates)));
}
public void SetSkyLight(Coordinates3D coordinates, byte value)
{
IChunk chunk;
var adjustedCoordinates = FindBlockPosition(coordinates, out chunk);
BlockDescriptor old = new BlockDescriptor();
if (BlockChanged != null)
old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates);
chunk.SetSkyLight(adjustedCoordinates, value);
if (BlockChanged != null)
BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates)));
}
public void SetBlockLight(Coordinates3D coordinates, byte value)
{
IChunk chunk;
var adjustedCoordinates = FindBlockPosition(coordinates, out chunk);
BlockDescriptor old = new BlockDescriptor();
if (BlockChanged != null)
old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates);
chunk.SetBlockLight(adjustedCoordinates, value);
if (BlockChanged != null)
BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates)));
}
public void SetTileEntity(Coordinates3D coordinates, NbtCompound value)
{
IChunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
chunk.SetTileEntity(coordinates, value);
}
public void Save()
{
lock (Regions)
{
foreach (var region in Regions)
region.Value.Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(region.Key)));
}
var file = new NbtFile();
file.RootTag.Add(new NbtCompound("SpawnPoint", new[]
{
new NbtInt("X", this.SpawnPoint.X),
new NbtInt("Y", this.SpawnPoint.Y),
new NbtInt("Z", this.SpawnPoint.Z)
}));
file.RootTag.Add(new NbtInt("Seed", this.Seed));
file.RootTag.Add(new NbtString("ChunkProvider", this.ChunkProvider.GetType().FullName));
file.RootTag.Add(new NbtString("Name", Name));
file.SaveToFile(Path.Combine(this.BaseDirectory, "manifest.nbt"), NbtCompression.ZLib);
}
public void Save(string path)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
BaseDirectory = path;
Save();
}
private Dictionary<Thread, IChunk> ChunkCache = new Dictionary<Thread, IChunk>();
private object ChunkCacheLock = new object();
public Coordinates3D FindBlockPosition(Coordinates3D coordinates, out IChunk chunk, bool generate = true)
{
if (coordinates.Y < 0 || coordinates.Y >= Chunk.Height)
throw new ArgumentOutOfRangeException("coordinates", "Coordinates are out of range");
int chunkX = coordinates.X / Chunk.Width;
int chunkZ = coordinates.Z / Chunk.Depth;
if (coordinates.X < 0)
chunkX = (coordinates.X + 1) / Chunk.Width - 1;
if (coordinates.Z < 0)
chunkZ = (coordinates.Z + 1) / Chunk.Depth - 1;
if (ChunkCache.ContainsKey(Thread.CurrentThread))
{
var cache = ChunkCache[Thread.CurrentThread];
if (cache != null && chunkX == cache.Coordinates.X && chunkZ == cache.Coordinates.Z)
chunk = cache;
else
{
cache = GetChunk(new Coordinates2D(chunkX, chunkZ), generate);
lock (ChunkCacheLock)
ChunkCache[Thread.CurrentThread] = cache;
}
}
else
{
var cache = GetChunk(new Coordinates2D(chunkX, chunkZ), generate);
lock (ChunkCacheLock)
ChunkCache[Thread.CurrentThread] = cache;
}
chunk = GetChunk(new Coordinates2D(chunkX, chunkZ), generate);
return new Coordinates3D(
(coordinates.X % Chunk.Width + Chunk.Width) % Chunk.Width,
coordinates.Y,
(coordinates.Z % Chunk.Depth + Chunk.Depth) % Chunk.Depth);
}
public bool IsValidPosition(Coordinates3D position)
{
return position.Y >= 0 && position.Y < Chunk.Height;
}
private Region LoadOrGenerateRegion(Coordinates2D coordinates, bool generate = true)
{
if (Regions.ContainsKey(coordinates))
return (Region)Regions[coordinates];
if (!generate)
return null;
Region region;
if (BaseDirectory != null)
{
var file = Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates));
if (File.Exists(file))
region = new Region(coordinates, this, file);
else
region = new Region(coordinates, this);
}
else
region = new Region(coordinates, this);
lock (Regions)
Regions[coordinates] = region;
return region;
}
public void Dispose()
{
foreach (var region in Regions)
region.Value.Dispose();
BlockChanged = null;
ChunkGenerated = null;
}
protected internal void OnChunkGenerated(ChunkLoadedEventArgs e)
{
if (ChunkGenerated != null)
ChunkGenerated(this, e);
}
protected internal void OnChunkLoaded(ChunkLoadedEventArgs e)
{
if (ChunkLoaded != null)
ChunkLoaded(this, e);
}
public class ChunkEnumerator : IEnumerator<IChunk>
{
public World World { get; set; }
private int Index { get; set; }
private IList<IChunk> Chunks { get; set; }
public ChunkEnumerator(World world)
{
World = world;
Index = -1;
var regions = world.Regions.Values.ToList();
var chunks = new List<IChunk>();
foreach (var region in regions)
chunks.AddRange(region.Chunks.Values);
Chunks = chunks;
}
public bool MoveNext()
{
Index++;
return Index < Chunks.Count;
}
public void Reset()
{
Index = -1;
}
public void Dispose()
{
}
public IChunk Current
{
get
{
return Chunks[Index];
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
}
public IEnumerator<IChunk> GetEnumerator()
{
return new ChunkEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Reflection
{
using System;
using System.Reflection;
////using System.Reflection.Cache;
////using System.Reflection.Emit;
using System.Globalization;
using System.Threading;
////using System.Diagnostics;
////using System.Security.Permissions;
////using System.Collections;
////using System.Security;
////using System.Text;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
////using System.Runtime.InteropServices;
////using System.Runtime.Serialization;
////using System.Runtime.Versioning;
////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
////using CorElementType = System.Reflection.CorElementType;
////using MdToken = System.Reflection.MetadataToken;
[Serializable]
internal sealed class RuntimeMethodInfo : MethodInfo /*, ISerializable*/
{
#region Static Members
//// internal static string ConstructParameters( ParameterInfo[] parameters, CallingConventions callingConvention )
//// {
//// Type[] parameterTypes = new Type[parameters.Length];
////
//// for(int i = 0; i < parameters.Length; i++)
//// {
//// parameterTypes[i] = parameters[i].ParameterType;
//// }
////
//// return ConstructParameters( parameterTypes, callingConvention );
//// }
////
//// internal static string ConstructParameters( Type[] parameters, CallingConventions callingConvention )
//// {
//// string toString = "";
//// string comma = "";
////
//// for(int i = 0; i < parameters.Length; i++)
//// {
//// Type t = parameters[i];
////
//// toString += comma;
//// toString += t.SigToString();
//// if(t.IsByRef)
//// {
//// toString = toString.TrimEnd( new char[] { '&' } );
//// toString += " ByRef";
//// }
////
//// comma = ", ";
//// }
////
//// if((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
//// {
//// toString += comma;
//// toString += "...";
//// }
////
//// return toString;
//// }
////
//// internal static string ConstructName( MethodBase mi )
//// {
//// // Serialization uses ToString to resolve MethodInfo overloads.
//// string toString = null;
////
//// toString += mi.Name;
////
//// RuntimeMethodInfo rmi = mi as RuntimeMethodInfo;
////
//// if(rmi != null && rmi.IsGenericMethod)
//// {
//// toString += rmi.m_handle.ConstructInstantiation();
//// }
////
//// toString += "(" + ConstructParameters( mi.GetParametersNoCopy(), mi.CallingConvention ) + ")";
////
//// return toString;
//// }
#endregion
#region Private Data Members
#pragma warning disable 169 // The private field 'class member' is never used
private RuntimeMethodHandle m_handle;
#pragma warning restore 169
//// private RuntimeTypeCache m_reflectedTypeCache;
//// private string m_name;
//// private string m_toString;
//// private ParameterInfo[] m_parameters;
//// private ParameterInfo m_returnParameter;
//// private BindingFlags m_bindingFlags;
//// private MethodAttributes m_methodAttributes;
//// private Signature m_signature;
//// private RuntimeType m_declaringType;
//// private uint m_invocationFlags;
#endregion
#region Constructor
internal RuntimeMethodInfo()
{
// Used for dummy head node during population
}
//// internal RuntimeMethodInfo( RuntimeMethodHandle handle ,
//// RuntimeTypeHandle declaringTypeHandle,
//// RuntimeTypeCache reflectedTypeCache ,
//// MethodAttributes methodAttributes ,
//// BindingFlags bindingFlags )
//// {
//// ASSERT.PRECONDITION( !handle.IsNullHandle() );
//// ASSERT.PRECONDITION( methodAttributes == handle.GetAttributes() );
////
//// m_toString = null;
//// m_bindingFlags = bindingFlags;
//// m_handle = handle;
//// m_reflectedTypeCache = reflectedTypeCache;
//// m_parameters = null; // Created lazily when GetParameters() is called.
//// m_methodAttributes = methodAttributes;
//// m_declaringType = declaringTypeHandle.GetRuntimeType();
////
//// ASSERT.POSTCONDITION( !m_handle.IsNullHandle() );
//// }
#endregion
#region Private Methods
//// private RuntimeTypeHandle ReflectedTypeHandle
//// {
//// get
//// {
//// return m_reflectedTypeCache.RuntimeTypeHandle;
//// }
//// }
////
//// internal ParameterInfo[] FetchNonReturnParameters()
//// {
//// if(m_parameters == null)
//// {
//// m_parameters = ParameterInfo.GetParameters( this, this, Signature );
//// }
////
//// return m_parameters;
//// }
////
//// internal ParameterInfo FetchReturnParameter()
//// {
//// if(m_returnParameter == null)
//// {
//// m_returnParameter = ParameterInfo.GetReturnParameter( this, this, Signature );
//// }
////
//// return m_returnParameter;
//// }
////
#endregion
#region Internal Members
//// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
//// internal override bool CacheEquals( object o )
//// {
//// RuntimeMethodInfo m = o as RuntimeMethodInfo;
////
//// if(m == null)
//// {
//// return false;
//// }
////
//// return m.m_handle.Equals( m_handle );
//// }
////
//// internal Signature Signature
//// {
//// get
//// {
//// if(m_signature == null)
//// {
//// m_signature = new Signature( m_handle, m_declaringType.GetTypeHandleInternal() );
//// }
////
//// return m_signature;
//// }
//// }
////
//// internal BindingFlags BindingFlags
//// {
//// get
//// {
//// return m_bindingFlags;
//// }
//// }
////
//// internal override RuntimeMethodHandle GetMethodHandle()
//// {
//// return m_handle;
//// }
////
//// internal override MethodInfo GetParentDefinition()
//// {
//// if(!IsVirtual || m_declaringType.IsInterface)
//// {
//// return null;
//// }
////
//// Type parent = m_declaringType.BaseType;
////
//// if(parent == null)
//// {
//// return null;
//// }
////
//// int slot = m_handle.GetSlot();
////
//// if(parent.GetTypeHandleInternal().GetNumVtableSlots() <= slot)
//// {
//// return null;
//// }
////
//// return (MethodInfo)RuntimeType.GetMethodBase( parent.GetTypeHandleInternal(), parent.GetTypeHandleInternal().GetMethodAt( slot ) );
//// }
////
//// internal override uint GetOneTimeFlags()
//// {
//// uint invocationFlags = 0;
////
//// if(ReturnType.IsByRef)
//// {
//// invocationFlags = INVOCATION_FLAGS_NO_INVOKE;
//// }
////
//// invocationFlags |= base.GetOneTimeFlags();
////
//// return invocationFlags;
//// }
#endregion
#region Object Overrides
//// public override String ToString()
//// {
//// if(m_toString == null)
//// {
//// m_toString = ReturnType.SigToString() + " " + ConstructName( this );
//// }
////
//// return m_toString;
//// }
////
//// public override int GetHashCode()
//// {
//// return m_handle.GetHashCode();
//// }
////
//// public override bool Equals( object obj )
//// {
//// if(!IsGenericMethod)
//// {
//// return obj == this;
//// }
////
//// RuntimeMethodInfo mi = obj as RuntimeMethodInfo;
////
//// RuntimeMethodHandle handle1 = GetMethodHandle().StripMethodInstantiation();
//// RuntimeMethodHandle handle2 = mi.GetMethodHandle().StripMethodInstantiation();
//// if(handle1 != handle2)
//// {
//// return false;
//// }
////
//// if(mi == null || !mi.IsGenericMethod)
//// {
//// return false;
//// }
////
//// Type[] lhs = GetGenericArguments();
//// Type[] rhs = mi.GetGenericArguments();
////
//// if(lhs.Length != rhs.Length)
//// {
//// return false;
//// }
////
//// for(int i = 0; i < lhs.Length; i++)
//// {
//// if(lhs[i] != rhs[i])
//// {
//// return false;
//// }
//// }
////
//// return true;
//// }
#endregion
#region ICustomAttributeProvider
[MethodImpl( MethodImplOptions.InternalCall )]
public extern override Object[] GetCustomAttributes( bool inherit );
//// {
//// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType as RuntimeType, inherit );
//// }
[MethodImpl( MethodImplOptions.InternalCall )]
public extern override 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, inherit );
//// }
[MethodImpl( MethodImplOptions.InternalCall )]
public extern override 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" ), "attributeType" );
//// }
////
//// return CustomAttribute.IsDefined( this, attributeRuntimeType, inherit );
//// }
#endregion
#region MemberInfo Overrides
public override String Name
{
//// [MethodImpl( MethodImplOptions.InternalCall )]
get
{
throw new NotImplementedException();
//// if(m_name == null)
//// {
//// m_name = m_handle.GetName();
//// }
////
//// return m_name;
}
}
public override Type DeclaringType
{
get
{
throw new NotImplementedException();
//// if(m_reflectedTypeCache.IsGlobal)
//// {
//// return null;
//// }
////
//// return m_declaringType;
}
}
//// public override Type ReflectedType
//// {
//// get
//// {
//// if(m_reflectedTypeCache.IsGlobal)
//// {
//// return null;
//// }
////
//// return m_reflectedTypeCache.RuntimeType;
//// }
//// }
public override MemberTypes MemberType
{
get
{
return MemberTypes.Method;
}
}
//// public override int MetadataToken
//// {
//// get
//// {
//// return m_handle.GetMethodDef();
//// }
//// }
////
//// public override Module Module
//// {
//// get
//// {
//// return m_declaringType.Module;
//// }
//// }
#endregion
#region MethodBase Overrides
//// internal override ParameterInfo[] GetParametersNoCopy()
//// {
//// FetchNonReturnParameters();
////
//// return m_parameters;
//// }
[MethodImpl( MethodImplOptions.InternalCall )]
public extern override ParameterInfo[] GetParameters();
//// {
//// FetchNonReturnParameters();
////
//// if(m_parameters.Length == 0)
//// {
//// return m_parameters;
//// }
////
//// ParameterInfo[] ret = new ParameterInfo[m_parameters.Length];
////
//// Array.Copy( m_parameters, ret, m_parameters.Length );
////
//// return ret;
//// }
////
//// public override MethodImplAttributes GetMethodImplementationFlags()
//// {
//// return m_handle.GetImplAttributes();
//// }
////
//// internal override bool IsOverloaded
//// {
//// get
//// {
//// return m_reflectedTypeCache.GetMethodList( MemberListType.CaseSensitive, Name ).Count > 1;
//// }
//// }
////
//// public override RuntimeMethodHandle MethodHandle
//// {
//// get
//// {
//// Type declaringType = DeclaringType;
//// if((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
//// {
//// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_NotAllowedInReflectionOnly" ) );
//// }
////
//// return m_handle;
//// }
//// }
////
//// public override MethodAttributes Attributes
//// {
//// get
//// {
//// return m_methodAttributes;
//// }
//// }
////
//// public override CallingConventions CallingConvention
//// {
//// get
//// {
//// return Signature.CallingConvention;
//// }
//// }
////
//// [ReflectionPermissionAttribute( SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess )]
//// public override MethodBody GetMethodBody()
//// {
//// MethodBody mb = m_handle.GetMethodBody( ReflectedTypeHandle );
//// if(mb != null)
//// {
//// mb.m_methodBase = this;
//// }
////
//// return mb;
//// }
#endregion
#region Invocation Logic(On MemberBase)
//// private void CheckConsistency( Object target )
//// {
//// // only test instance methods
//// if((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
//// {
//// if(!m_declaringType.IsInstanceOfType( target ))
//// {
//// if(target == null)
//// {
//// throw new TargetException( Environment.GetResourceString( "RFLCT.Targ_StatMethReqTarg" ) );
//// }
//// else
//// {
//// throw new TargetException( Environment.GetResourceString( "RFLCT.Targ_ITargMismatch" ) );
//// }
//// }
//// }
//// }
////
//// private void ThrowNoInvokeException()
//// {
//// // method is ReflectionOnly
//// Type declaringType = DeclaringType;
//// if((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
//// {
//// throw new InvalidOperationException( Environment.GetResourceString( "Arg_ReflectionOnlyInvoke" ) );
//// }
////
//// // method is on a class that contains stack pointers
//// if(DeclaringType.GetRootElementType() == typeof( ArgIterator ))
//// {
//// throw new NotSupportedException();
//// }
//// // method is vararg
//// else if((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
//// {
//// throw new NotSupportedException();
//// }
//// // method is generic or on a generic class
//// else if(DeclaringType.ContainsGenericParameters || ContainsGenericParameters)
//// {
//// throw new InvalidOperationException( Environment.GetResourceString( "Arg_UnboundGenParam" ) );
//// }
//// // method is abstract class
//// else if(IsAbstract)
//// {
//// throw new MemberAccessException();
//// }
//// // ByRef return are not allowed in reflection
//// else if(ReturnType.IsByRef)
//// {
//// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ByRefReturn" ) );
//// }
////
//// throw new TargetException();
//// }
////
//// [DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImpl( MethodImplOptions.InternalCall )]
public extern override Object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture );
//// {
//// return Invoke( obj, invokeAttr, binder, parameters, culture, false );
//// }
////
//// [DebuggerStepThroughAttribute]
//// [Diagnostics.DebuggerHidden]
//// internal object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, bool skipVisibilityChecks )
//// {
//// // get the signature
//// int formalCount = Signature.Arguments.Length;
//// int actualCount = (parameters != null) ? parameters.Length : 0;
////
//// // set one time info for invocation
//// if((m_invocationFlags & INVOCATION_FLAGS_INITIALIZED) == 0)
//// {
//// m_invocationFlags = GetOneTimeFlags();
//// }
////
//// if((m_invocationFlags & INVOCATION_FLAGS_NO_INVOKE) != 0)
//// {
//// ThrowNoInvokeException();
//// }
////
//// // check basic method consistency. This call will throw if there are problems in the target/method relationship
//// CheckConsistency( obj );
////
//// if(formalCount != actualCount)
//// {
//// throw new TargetParameterCountException( Environment.GetResourceString( "Arg_ParmCnt" ) );
//// }
////
//// // Don't allow more than 65535 parameters.
//// if(actualCount > UInt16.MaxValue)
//// {
//// throw new TargetParameterCountException( Environment.GetResourceString( "NotSupported_TooManyArgs" ) );
//// }
////
//// if(!skipVisibilityChecks && (m_invocationFlags & (INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS_NEED_SECURITY)) != 0)
//// {
//// if((m_invocationFlags & INVOCATION_FLAGS_RISKY_METHOD) != 0)
//// {
//// CodeAccessPermission.DemandInternal( PermissionType.ReflectionMemberAccess );
//// }
////
//// if((m_invocationFlags & INVOCATION_FLAGS_NEED_SECURITY) != 0)
//// {
//// PerformSecurityCheck( obj, m_handle, m_declaringType.TypeHandle.Value, m_invocationFlags );
//// }
//// }
////
//// // if we are here we passed all the previous checks. Time to look at the arguments
//// RuntimeTypeHandle declaringTypeHandle = RuntimeTypeHandle.EmptyHandle;
//// if(!m_reflectedTypeCache.IsGlobal)
//// {
//// declaringTypeHandle = m_declaringType.TypeHandle;
//// }
////
//// if(actualCount == 0)
//// {
//// return m_handle.InvokeMethodFast( obj, null, Signature, m_methodAttributes, declaringTypeHandle );
//// }
////
//// Object[] arguments = CheckArguments( parameters, binder, invokeAttr, culture, Signature );
////
//// Object retValue = m_handle.InvokeMethodFast( obj, arguments, Signature, m_methodAttributes, declaringTypeHandle );
////
//// // copy out. This should be made only if ByRef are present.
//// for(int index = 0; index < actualCount; index++)
//// {
//// parameters[index] = arguments[index];
//// }
////
//// return retValue;
//// }
#endregion
#region MethodInfo Overrides
//// public override Type ReturnType
//// {
//// get
//// {
//// return Signature.ReturnTypeHandle.GetRuntimeType();
//// }
//// }
////
//// public override ICustomAttributeProvider ReturnTypeCustomAttributes
//// {
//// get
//// {
//// return ReturnParameter;
//// }
//// }
////
//// public override ParameterInfo ReturnParameter
//// {
//// get
//// {
//// FetchReturnParameter();
//// ASSERT.POSTCONDITION( m_returnParameter != null );
//// return m_returnParameter as ParameterInfo;
//// }
//// }
////
//// public override MethodInfo GetBaseDefinition()
//// {
//// if(!IsVirtual || m_declaringType.IsInterface)
//// {
//// return this;
//// }
////
//// int slot = m_handle.GetSlot();
//// RuntimeTypeHandle parent = m_handle.GetDeclaringType();
//// RuntimeMethodHandle baseMethodHandle = RuntimeMethodHandle.EmptyHandle;
////
//// do
//// {
//// int cVtblSlots = parent.GetNumVtableSlots();
////
//// if(cVtblSlots <= slot)
//// {
//// break;
//// }
////
//// baseMethodHandle = parent.GetMethodAt( slot );
//// parent = baseMethodHandle.GetDeclaringType().GetBaseTypeHandle();
//// } while(!parent.IsNullHandle());
////
//// ASSERT.CONSISTENCY_CHECK( (baseMethodHandle.GetAttributes() & MethodAttributes.Virtual) != 0 );
////
//// return (MethodInfo)RuntimeType.GetMethodBase( baseMethodHandle );
//// }
#endregion
#region Generics
//// public override MethodInfo MakeGenericMethod( params Type[] methodInstantiation )
//// {
//// if(methodInstantiation == null)
//// {
//// throw new ArgumentNullException( "methodInstantiation" );
//// }
////
//// Type[] methodInstantiationCopy = new Type[methodInstantiation.Length];
//// for(int i = 0; i < methodInstantiation.Length; i++)
//// {
//// methodInstantiationCopy[i] = methodInstantiation[i];
//// }
//// methodInstantiation = methodInstantiationCopy;
////
//// if(!IsGenericMethodDefinition)
//// {
//// throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_NotGenericMethodDefinition" ), this ) );
//// }
////
//// for(int i = 0; i < methodInstantiation.Length; i++)
//// {
//// if(methodInstantiation[i] == null)
//// {
//// throw new ArgumentNullException();
//// }
////
//// if(!(methodInstantiation[i] is RuntimeType))
//// {
//// return MethodBuilderInstantiation.MakeGenericMethod( this, methodInstantiation );
//// }
//// }
////
//// Type[] genericParameters = GetGenericArguments();
////
//// RuntimeType.SanityCheckGenericArguments( methodInstantiation, genericParameters );
////
//// RuntimeTypeHandle[] typeHandles = new RuntimeTypeHandle[methodInstantiation.Length];
////
//// for(int i = 0; i < methodInstantiation.Length; i++)
//// {
//// typeHandles[i] = methodInstantiation[i].GetTypeHandleInternal();
//// }
////
//// MethodInfo ret = null;
////
//// try
//// {
//// ret = RuntimeType.GetMethodBase( m_reflectedTypeCache.RuntimeTypeHandle, m_handle.GetInstantiatingStub( m_declaringType.GetTypeHandleInternal(), typeHandles ) ) as MethodInfo;
//// }
//// catch(VerificationException e)
//// {
//// RuntimeType.ValidateGenericArguments( this, methodInstantiation, e );
//// throw e;
//// }
////
//// return ret;
//// }
////
//// public override Type[] GetGenericArguments()
//// {
//// RuntimeType[] rtypes = null;
//// RuntimeTypeHandle[] types = m_handle.GetMethodInstantiation();
////
//// if(types != null)
//// {
//// rtypes = new RuntimeType[types.Length];
////
//// for(int i = 0; i < types.Length; i++)
//// {
//// rtypes[i] = types[i].GetRuntimeType();
//// }
//// }
//// else
//// {
//// rtypes = new RuntimeType[0];
//// }
////
//// return rtypes;
//// }
////
//// public override MethodInfo GetGenericMethodDefinition()
//// {
//// if(!IsGenericMethod)
//// {
//// throw new InvalidOperationException();
//// }
////
//// return RuntimeType.GetMethodBase( m_declaringType.GetTypeHandleInternal(), m_handle.StripMethodInstantiation() ) as MethodInfo;
//// }
////
//// public override bool IsGenericMethod
//// {
//// get
//// {
//// return m_handle.HasMethodInstantiation();
//// }
//// }
////
//// public override bool IsGenericMethodDefinition
//// {
//// get
//// {
//// return m_handle.IsGenericMethodDefinition();
//// }
//// }
////
//// public override bool ContainsGenericParameters
//// {
//// get
//// {
//// if(DeclaringType != null && DeclaringType.ContainsGenericParameters)
//// {
//// return true;
//// }
////
//// if(!IsGenericMethod)
//// {
//// return false;
//// }
////
//// Type[] pis = GetGenericArguments();
//// for(int i = 0; i < pis.Length; i++)
//// {
//// if(pis[i].ContainsGenericParameters)
//// {
//// return true;
//// }
//// }
////
//// return false;
//// }
//// }
#endregion
#region ISerializable Implementation
//// public void GetObjectData( SerializationInfo info, StreamingContext context )
//// {
//// if(info == null)
//// {
//// throw new ArgumentNullException( "info" );
//// }
////
//// if(m_reflectedTypeCache.IsGlobal)
//// {
//// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GlobalMethodSerialization" ) );
//// }
////
//// MemberInfoSerializationHolder.GetSerializationInfo(
//// info, Name, ReflectedTypeHandle.GetRuntimeType(), ToString(), MemberTypes.Method,
//// IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null );
//// }
#endregion
#region Legacy Internal
//// internal static MethodBase InternalGetCurrentMethod( ref StackCrawlMark stackMark )
//// {
//// RuntimeMethodHandle method = RuntimeMethodHandle.GetCurrentMethod( ref stackMark );
////
//// if(method.IsNullHandle())
//// {
//// return null;
//// }
////
//// // If C<Foo>.m<Bar> was called, GetCurrentMethod returns C<object>.m<object>. We cannot
//// // get know that the instantiation used Foo or Bar at that point. So the next best thing
//// // is to return C<T>.m<P> and that's what GetTypicalMethodDefinition will do for us.
//// method = method.GetTypicalMethodDefinition();
////
//// return RuntimeType.GetMethodBase( method );
//// }
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2016 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.Threading;
using NUnit.Framework;
using NUnit.Framework.Constraints;
#if ASYNC
using System.Threading.Tasks;
#endif
#if NET40
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.TestData
{
[TestFixture]
public class WarningFixture
{
#region Passing Tests
[Test]
public void WarnUnless_Passes_Boolean()
{
Warn.Unless(2 + 2 == 4);
}
[Test]
public void WarnIf_Passes_Boolean()
{
Warn.If(2 + 2 != 4);
}
[Test]
public void WarnUnless_Passes_BooleanWithMessage()
{
Warn.Unless(2 + 2 == 4, "Not Equal");
}
[Test]
public void WarnIf_Passes_BooleanWithMessage()
{
Warn.If(2 + 2 != 4, "Not Equal");
}
[Test]
public void WarnUnless_Passes_BooleanWithMessageAndArgs()
{
Warn.Unless(2 + 2 == 4, "Not Equal to {0}", 4);
}
[Test]
public void WarnIf_Passes_BooleanWithMessageAndArgs()
{
Warn.If(2 + 2 != 4, "Not Equal to {0}", 4);
}
[Test]
public void WarnUnless_Passes_BooleanWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.Unless(2 + 2 == 4, getExceptionMessage);
}
[Test]
public void WarnIf_Passes_BooleanWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.If(2 + 2 != 4, getExceptionMessage);
}
[Test]
public void WarnUnless_Passes_BooleanLambda()
{
Warn.Unless(() => 2 + 2 == 4);
}
[Test]
public void WarnIf_Passes_BooleanLambda()
{
Warn.If(() => 2 + 2 != 4);
}
[Test]
public void WarnUnless_Passes_BooleanLambdaWithMessage()
{
Warn.Unless(() => 2 + 2 == 4, "Not Equal");
}
[Test]
public void WarnIf_Passes_BooleanLambdaWithMessage()
{
Warn.If(() => 2 + 2 != 4, "Not Equal");
}
[Test]
public void WarnUnless_Passes_BooleanLambdaWithMessageAndArgs()
{
Warn.Unless(() => 2 + 2 == 4, "Not Equal to {0}", 4);
}
[Test]
public void WarnIf_Passes_BooleanLambdaWithMessageAndArgs()
{
Warn.If(() => 2 + 2 != 4, "Not Equal to {0}", 4);
}
[Test]
public void WarnUnless_Passes_BooleanLambdaWithWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.Unless(() => 2 + 2 == 4, getExceptionMessage);
}
[Test]
public void WarnIf_Passes_BooleanLambdaWithWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.If(() => 2 + 2 != 4, getExceptionMessage);
}
[Test]
public void WarnUnless_Passes_ActualAndConstraint()
{
Warn.Unless(2 + 2, Is.EqualTo(4));
}
[Test]
public void WarnIf_Passes_ActualAndConstraint()
{
Warn.If(2 + 2, Is.Not.EqualTo(4));
}
[Test]
public void WarnUnless_Passes_ActualAndConstraintWithMessage()
{
Warn.Unless(2 + 2, Is.EqualTo(4), "Should be 4");
}
[Test]
public void WarnIf_Passes_ActualAndConstraintWithMessage()
{
Warn.If(2 + 2, Is.Not.EqualTo(4), "Should be 4");
}
[Test]
public void WarnUnless_Passes_ActualAndConstraintWithMessageAndArgs()
{
Warn.Unless(2 + 2, Is.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void WarnIf_Passes_ActualAndConstraintWithMessageAndArgs()
{
Warn.If(2 + 2, Is.Not.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void WarnUnless_Passes_ActualAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.Unless(2 + 2, Is.EqualTo(4), getExceptionMessage);
}
[Test]
public void WarnIf_Passes_ActualAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.If(2 + 2, Is.Not.EqualTo(4), getExceptionMessage);
}
[Test]
public void WarnUnless_Passes_ActualLambdaAndConstraint()
{
Warn.Unless(() => 2 + 2, Is.EqualTo(4));
}
[Test]
public void WarnIf_Passes_ActualLambdaAndConstraint()
{
Warn.If(() => 2 + 2, Is.Not.EqualTo(4));
}
[Test]
public void WarnUnless_Passes_ActualLambdaAndConstraintWithMessage()
{
Warn.Unless(() => 2 + 2, Is.EqualTo(4), "Should be 4");
}
[Test]
public void WarnIf_Passes_ActualLambdaAndConstraintWithMessage()
{
Warn.If(() => 2 + 2, Is.Not.EqualTo(4), "Should be 4");
}
[Test]
public void WarnUnless_Passes_ActualLambdaAndConstraintWithMessageAndArgs()
{
Warn.Unless(() => 2 + 2, Is.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void WarnIf_Passes_ActualLambdaAndConstraintWithMessageAndArgs()
{
Warn.If(() => 2 + 2, Is.Not.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void WarnUnless_Passes_ActualLambdaAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.Unless(() => 2 + 2, Is.EqualTo(4), getExceptionMessage);
}
[Test]
public void WarnIf_Passes_ActualLambdaAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.If(() => 2 + 2, Is.Not.EqualTo(4), getExceptionMessage);
}
[Test]
public void WarnUnless_Passes_DelegateAndConstraint()
{
Warn.Unless(new ActualValueDelegate<int>(ReturnsFour), Is.EqualTo(4));
}
[Test]
public void WarnIf_Passes_DelegateAndConstraint()
{
Warn.If(new ActualValueDelegate<int>(ReturnsFour), Is.Not.EqualTo(4));
}
[Test]
public void WarnUnless_Passes_DelegateAndConstraintWithMessage()
{
Warn.Unless(new ActualValueDelegate<int>(ReturnsFour), Is.EqualTo(4), "Message");
}
[Test]
public void WarnIf_Passes_DelegateAndConstraintWithMessage()
{
Warn.If(new ActualValueDelegate<int>(ReturnsFour), Is.Not.EqualTo(4), "Message");
}
[Test]
public void WarnUnless_Passes_DelegateAndConstraintWithMessageAndArgs()
{
Warn.Unless(new ActualValueDelegate<int>(ReturnsFour), Is.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void WarnIf_Passes_DelegateAndConstraintWithMessageAndArgs()
{
Warn.If(new ActualValueDelegate<int>(ReturnsFour), Is.Not.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void WarnUnless_Passes_DelegateAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.Unless(new ActualValueDelegate<int>(ReturnsFour), Is.EqualTo(4), getExceptionMessage);
}
[Test]
public void WarnIf_Passes_DelegateAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Warn.If(new ActualValueDelegate<int>(ReturnsFour), Is.Not.EqualTo(4), getExceptionMessage);
}
#if ASYNC
[Test]
public void WarnUnless_Passes_Async()
{
Warn.Unless(async () => await One(), Is.EqualTo(1));
}
[Test]
public void WarnIf_Passes_Async()
{
Warn.If(async () => await One(), Is.Not.EqualTo(1));
}
#endif
#endregion
#region Tests that issue Warnings
[Test]
public void CallAssertWarnWithMessage()
{
Assert.Warn("MESSAGE");
}
[Test]
public void CallAssertWarnWithMessageAndArgs()
{
Assert.Warn("MESSAGE: {0}+{1}={2}", 2, 2, 4);
}
[Test]
public void WarnUnless_Fails_Boolean()
{
Warn.Unless(2 + 2 == 5);
}
[Test]
public void WarnIf_Fails_Boolean()
{
Warn.If(2 + 2 != 5);
}
[Test]
public void WarnUnless_Fails_BooleanWithMessage()
{
Warn.Unless(2 + 2 == 5, "message");
}
[Test]
public void WarnIf_Fails_BooleanWithMessage()
{
Warn.If(2 + 2 != 5, "message");
}
[Test]
public void WarnUnless_Fails_BooleanWithMessageAndArgs()
{
Warn.Unless(2 + 2 == 5, "got {0}", 5);
}
[Test]
public void WarnIf_Fails_BooleanWithMessageAndArgs()
{
Warn.If(2 + 2 != 5, "got {0}", 5);
}
[Test]
public void WarnUnless_Fails_BooleanWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "got 5";
Warn.Unless(2 + 2 == 5, getExceptionMessage);
}
[Test]
public void WarnIf_Fails_BooleanWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "got 5";
Warn.If(2 + 2 != 5, getExceptionMessage);
}
[Test]
public void WarnUnless_Fails_BooleanLambda()
{
Warn.Unless(() => 2 + 2 == 5);
}
[Test]
public void WarnIf_Fails_BooleanLambda()
{
Warn.If(() => 2 + 2 != 5);
}
[Test]
public void WarnUnless_Fails_BooleanLambdaWithMessage()
{
Warn.Unless(() => 2 + 2 == 5, "message");
}
[Test]
public void WarnIf_Fails_BooleanLambdaWithMessage()
{
Warn.If(() => 2 + 2 != 5, "message");
}
[Test]
public void WarnUnless_Fails_BooleanLambdaWithMessageAndArgs()
{
Warn.Unless(() => 2 + 2 == 5, "got {0}", 5);
}
[Test]
public void WarnIf_Fails_BooleanLambdaWithMessageAndArgs()
{
Warn.If(() => 2 + 2 != 5, "got {0}", 5);
}
[Test]
public void WarnUnless_Fails_BooleanLambdaWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "got 5";
Warn.Unless(() => 2 + 2 == 5, getExceptionMessage);
}
[Test]
public void WarnIf_Fails_BooleanLambdaWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "got 5";
Warn.If(() => 2 + 2 != 5, getExceptionMessage);
}
[Test]
public void WarnUnless_Fails_ActualAndConstraint()
{
Warn.Unless(2 + 2, Is.EqualTo(5));
}
[Test]
public void WarnIf_Fails_ActualAndConstraint()
{
Warn.If(2 + 2, Is.Not.EqualTo(5));
}
[Test]
public void WarnUnless_Fails_ActualAndConstraintWithMessage()
{
Warn.Unless(2 + 2, Is.EqualTo(5), "Error");
}
[Test]
public void WarnIf_Fails_ActualAndConstraintWithMessage()
{
Warn.If(2 + 2, Is.Not.EqualTo(5), "Error");
}
[Test]
public void WarnUnless_Fails_ActualAndConstraintWithMessageAndArgs()
{
Warn.Unless(2 + 2, Is.EqualTo(5), "Should be {0}", 5);
}
[Test]
public void WarnIf_Fails_ActualAndConstraintWithMessageAndArgs()
{
Warn.If(2 + 2, Is.Not.EqualTo(5), "Should be {0}", 5);
}
[Test]
public void WarnUnless_Fails_ActualAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "Should be 5";
Warn.Unless(2 + 2, Is.EqualTo(5), getExceptionMessage);
}
[Test]
public void WarnIf_Fails_ActualAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "Should be 5";
Warn.If(2 + 2, Is.Not.EqualTo(5), getExceptionMessage);
}
[Test]
public void WarnUnless_Fails_ActualLambdaAndConstraint()
{
Warn.Unless(() => 2 + 2, Is.EqualTo(5));
}
[Test]
public void WarnIf_Fails_ActualLambdaAndConstraint()
{
Warn.If(() => 2 + 2, Is.Not.EqualTo(5));
}
[Test]
public void WarnUnless_Fails_ActualLambdaAndConstraintWithMessage()
{
Warn.Unless(() => 2 + 2, Is.EqualTo(5), "Error");
}
[Test]
public void WarnIf_Fails_ActualLambdaAndConstraintWithMessage()
{
Warn.If(() => 2 + 2, Is.Not.EqualTo(5), "Error");
}
[Test]
public void WarnUnless_Fails_ActualLambdaAndConstraintWithMessageAndArgs()
{
Warn.Unless(() => 2 + 2, Is.EqualTo(5), "Should be {0}", 5);
}
[Test]
public void WarnIf_Fails_ActualLambdaAndConstraintWithMessageAndArgs()
{
Warn.If(() => 2 + 2, Is.Not.EqualTo(5), "Should be {0}", 5);
}
[Test]
public void WarnUnless_Fails_ActualLambdaAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "Should be 5";
Warn.Unless(() => 2 + 2, Is.EqualTo(5), getExceptionMessage);
}
[Test]
public void WarnIf_Fails_ActualLambdaAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "Should be 5";
Warn.If(() => 2 + 2, Is.Not.EqualTo(5), getExceptionMessage);
}
[Test]
public void WarnUnless_Fails_DelegateAndConstraint()
{
Warn.Unless(new ActualValueDelegate<int>(ReturnsFive), Is.EqualTo(4));
}
[Test]
public void WarnIf_Fails_DelegateAndConstraint()
{
Warn.If(new ActualValueDelegate<int>(ReturnsFive), Is.Not.EqualTo(4));
}
[Test]
public void WarnUnless_Fails_DelegateAndConstraintWithMessage()
{
Warn.Unless(new ActualValueDelegate<int>(ReturnsFive), Is.EqualTo(4), "Error");
}
[Test]
public void WarnIf_Fails_DelegateAndConstraintWithMessage()
{
Warn.If(new ActualValueDelegate<int>(ReturnsFive), Is.Not.EqualTo(4), "Error");
}
[Test]
public void WarnUnless_Fails_DelegateAndConstraintWithMessageAndArgs()
{
Warn.Unless(new ActualValueDelegate<int>(ReturnsFive), Is.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void WarnIf_Fails_DelegateAndConstraintWithMessageAndArgs()
{
Warn.If(new ActualValueDelegate<int>(ReturnsFive), Is.Not.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void WarnUnless_Fails_DelegateAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "Should be 4";
Warn.Unless(new ActualValueDelegate<int>(ReturnsFive), Is.EqualTo(4), getExceptionMessage);
}
[Test]
public void WarnIf_Fails_DelegateAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "Should be 4";
Warn.If(new ActualValueDelegate<int>(ReturnsFive), Is.Not.EqualTo(4), getExceptionMessage);
}
#if ASYNC
[Test]
public void WarnUnless_Fails_Async()
{
Warn.Unless(async () => await One(), Is.EqualTo(2));
}
[Test]
public void WarnIf_Fails_Async()
{
Warn.If(async () => await One(), Is.Not.EqualTo(2));
}
#endif
#endregion
#region Warnings followed by terminating Assert
[Test]
public void TwoWarningsAndFailure()
{
Assert.Warn("First warning");
Assert.Warn("Second warning");
Assert.Fail("This fails");
}
[Test]
public void TwoWarningsAndIgnore()
{
Assert.Warn("First warning");
Assert.Warn("Second warning");
Assert.Ignore("Ignore this");
}
[Test]
public void TwoWarningsAndInconclusive()
{
Assert.Warn("First warning");
Assert.Warn("Second warning");
Assert.Inconclusive("This is inconclusive");
}
#endregion
#region Helper Methods
private int ReturnsFour()
{
return 4;
}
private int ReturnsFive()
{
return 5;
}
#if ASYNC
private static Task<int> One()
{
return Task.Run(() => 1);
}
#endif
#endregion
#region Stack filter tests
[Test]
public static void WarningSynchronous()
{
Assert.Warn("(Warning message)");
}
[Test]
public static void WarningInBeginInvoke()
{
using (var finished = new ManualResetEvent(false))
{
new Action(() =>
{
try
{
Assert.Warn("(Warning message)");
}
finally
{
finished.Set();
}
}).BeginInvoke(ar => { }, null);
if (!finished.WaitOne(10000)) Assert.Fail("Timeout while waiting for BeginInvoke to execute.");
}
}
[Test]
public static void WarningInThreadStart()
{
using (var finished = new ManualResetEvent(false))
{
new Thread(() =>
{
try
{
Assert.Warn("(Warning message)");
}
finally
{
finished.Set();
}
}).Start();
if (!finished.WaitOne(10000))
Assert.Fail("Timeout while waiting for threadstart to execute.");
}
}
[Test]
public static void WarningInThreadPoolQueueUserWorkItem()
{
using (var finished = new ManualResetEvent(false))
{
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
Assert.Warn("(Warning message)");
}
finally
{
finished.Set();
}
});
if (!finished.WaitOne(10000))
Assert.Fail("Timeout while waiting for Threadpool.QueueUserWorkItem to execute.");
}
}
#if ASYNC
[Test]
public static void WarningInTaskRun()
{
if (!Task.Run(() => Assert.Warn("(Warning message)")).Wait(10000))
Assert.Fail("Timeout while waiting for Task.Run to execute.");
}
[Test]
public static async System.Threading.Tasks.Task WarningAfterAwaitTaskDelay()
{
await Task.Delay(1);
Assert.Warn("(Warning message)");
}
#endif
#endregion
}
public abstract class WarningInSetUpOrTearDownFixture
{
[Test]
public void WarningPassesInTest()
{
Warn.Unless(2 + 2, Is.EqualTo(4));
}
[Test]
public void WarningFailsInTest()
{
Warn.Unless(2 + 2, Is.EqualTo(5));
}
[Test]
public void ThreeWarningsFailInTest()
{
Warn.Unless(2 + 2, Is.EqualTo(5));
Warn.Unless(2 + 2, Is.EqualTo(22));
Warn.Unless(2 + 2, Is.EqualTo(42));
}
}
public class WarningInSetUpPasses : WarningInSetUpOrTearDownFixture
{
[SetUp]
public void SetUp()
{
Warn.Unless(2 + 2, Is.EqualTo(4));
}
}
public class WarningInSetUpFails : WarningInSetUpOrTearDownFixture
{
[SetUp]
public void SetUp()
{
Warn.Unless(2 + 2, Is.EqualTo(5));
}
}
public class WarningInTearDownPasses : WarningInSetUpOrTearDownFixture
{
[TearDown]
public void TearDown()
{
Warn.Unless(2 + 2, Is.EqualTo(4));
}
}
public class WarningInTearDownFails : WarningInSetUpOrTearDownFixture
{
[TearDown]
public void TearDown()
{
Warn.Unless(2 + 2, Is.EqualTo(5));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
namespace Orleans.Runtime
{
/// <summary>
/// Data class encapsulating the details of silo addresses.
/// </summary>
[Serializable]
[DebuggerDisplay("SiloAddress {ToString()}")]
public class SiloAddress : IEquatable<SiloAddress>, IComparable<SiloAddress>
{
internal static readonly int SizeBytes = 24; // 16 for the address, 4 for the port, 4 for the generation
/// <summary> Special constant value to indicate an empty SiloAddress. </summary>
public static SiloAddress Zero { get; private set; }
private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_MEDIUM;
private static readonly TimeSpan internCacheCleanupInterval = TimeSpan.Zero;
private int hashCode = 0;
private bool hashCodeSet = false;
[NonSerialized]
private List<uint> uniformHashCache;
public IPEndPoint Endpoint { get; private set; }
public int Generation { get; private set; }
private const char SEPARATOR = '@';
private static readonly DateTime epoch = new DateTime(2010, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly Interner<SiloAddress, SiloAddress> siloAddressInterningCache;
private static readonly IPEndPoint localEndpoint = new IPEndPoint(ClusterConfiguration.GetLocalIPAddress(), 0); // non loopback local ip.
static SiloAddress()
{
siloAddressInterningCache = new Interner<SiloAddress, SiloAddress>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval);
var sa = new SiloAddress(new IPEndPoint(0, 0), 0);
Zero = siloAddressInterningCache.Intern(sa, sa);
}
/// <summary>
/// Factory for creating new SiloAddresses for silo on this machine with specified generation number.
/// </summary>
/// <param name="gen">Generation number of the silo.</param>
/// <returns>SiloAddress object initialized with the non-loopback local IP address and the specified silo generation.</returns>
public static SiloAddress NewLocalAddress(int gen)
{
return New(localEndpoint, gen);
}
/// <summary>
/// Factory for creating new SiloAddresses with specified IP endpoint address and silo generation number.
/// </summary>
/// <param name="ep">IP endpoint address of the silo.</param>
/// <param name="gen">Generation number of the silo.</param>
/// <returns>SiloAddress object initialized with specified address and silo generation.</returns>
public static SiloAddress New(IPEndPoint ep, int gen)
{
var sa = new SiloAddress(ep, gen);
return siloAddressInterningCache.Intern(sa, sa);
}
private SiloAddress(IPEndPoint endpoint, int gen)
{
Endpoint = endpoint;
Generation = gen;
}
public bool IsClient { get { return Generation < 0; } }
/// <summary> Allocate a new silo generation number. </summary>
/// <returns>A new silo generation number.</returns>
public static int AllocateNewGeneration()
{
long elapsed = (DateTime.UtcNow.Ticks - epoch.Ticks) / TimeSpan.TicksPerSecond;
return unchecked((int)elapsed); // Unchecked to truncate any bits beyond the lower 32
}
/// <summary>
/// Return this SiloAddress in a standard string form, suitable for later use with the <c>FromParsableString</c> method.
/// </summary>
/// <returns>SiloAddress in a standard string format.</returns>
public string ToParsableString()
{
// This must be the "inverse" of FromParsableString, and must be the same across all silos in a deployment.
// Basically, this should never change unless the data content of SiloAddress changes
return String.Format("{0}:{1}@{2}", Endpoint.Address, Endpoint.Port, Generation);
}
/// <summary>
/// Create a new SiloAddress object by parsing string in a standard form returned from <c>ToParsableString</c> method.
/// </summary>
/// <param name="addr">String containing the SiloAddress info to be parsed.</param>
/// <returns>New SiloAddress object created from the input data.</returns>
public static SiloAddress FromParsableString(string addr)
{
// This must be the "inverse" of ToParsableString, and must be the same across all silos in a deployment.
// Basically, this should never change unless the data content of SiloAddress changes
// First is the IPEndpoint; then '@'; then the generation
int atSign = addr.LastIndexOf(SEPARATOR);
if (atSign < 0)
{
throw new FormatException("Invalid string SiloAddress: " + addr);
}
var epString = addr.Substring(0, atSign);
var genString = addr.Substring(atSign + 1);
// IPEndpoint is the host, then ':', then the port
int lastColon = epString.LastIndexOf(':');
if (lastColon < 0) throw new FormatException("Invalid string SiloAddress: " + addr);
var hostString = epString.Substring(0, lastColon);
var portString = epString.Substring(lastColon + 1);
var host = IPAddress.Parse(hostString);
int port = Int32.Parse(portString);
return New(new IPEndPoint(host, port), Int32.Parse(genString));
}
/// <summary> Object.ToString method override. </summary>
public override string ToString()
{
return String.Format("{0}{1}:{2}", (IsClient ? "C" : "S"), Endpoint, Generation);
}
/// <summary>
/// Return a long string representation of this SiloAddress.
/// </summary>
/// <remarks>
/// Note: This string value is not comparable with the <c>FromParsableString</c> method -- use the <c>ToParsableString</c> method for that purpose.
/// </remarks>
/// <returns>String representaiton of this SiloAddress.</returns>
public string ToLongString()
{
return ToString();
}
/// <summary>
/// Return a long string representation of this SiloAddress, including it's consistent hash value.
/// </summary>
/// <remarks>
/// Note: This string value is not comparable with the <c>FromParsableString</c> method -- use the <c>ToParsableString</c> method for that purpose.
/// </remarks>
/// <returns>String representaiton of this SiloAddress.</returns>
public string ToStringWithHashCode()
{
return String.Format("{0}/x{1, 8:X8}", ToString(), GetConsistentHashCode());
}
/// <summary> Object.Equals method override. </summary>
public override bool Equals(object obj)
{
return Equals(obj as SiloAddress);
}
/// <summary> Object.GetHashCode method override. </summary>
public override int GetHashCode()
{
// Note that Port cannot be used because Port==0 matches any non-zero Port value for .Equals
return Endpoint.GetHashCode() ^ Generation.GetHashCode();
}
/// <summary>Get a consistent hash value for this silo address.</summary>
/// <returns>Consistent hash value for this silo address.</returns>
public int GetConsistentHashCode()
{
if (hashCodeSet) return hashCode;
// Note that Port cannot be used because Port==0 matches any non-zero Port value for .Equals
string siloAddressInfoToHash = Endpoint + Generation.ToString(CultureInfo.InvariantCulture);
hashCode = Utils.CalculateIdHash(siloAddressInfoToHash);
hashCodeSet = true;
return hashCode;
}
public List<uint> GetUniformHashCodes(int numHashes)
{
if (uniformHashCache != null) return uniformHashCache;
var jenkinsHash = JenkinsHash.Factory.GetHashGenerator();
var hashes = new List<uint>();
for (int i = 0; i < numHashes; i++)
{
uint hash = GetUniformHashCode(jenkinsHash, i);
hashes.Add(hash);
}
uniformHashCache = hashes;
return uniformHashCache;
}
private uint GetUniformHashCode(JenkinsHash jenkinsHash, int extraBit)
{
var writer = new BinaryTokenStreamWriter();
writer.Write(this);
writer.Write(extraBit);
byte[] bytes = writer.ToByteArray();
return jenkinsHash.ComputeHash(bytes);
}
/// <summary>
/// Two silo addresses match if they are equal or if one generation or the other is 0
/// </summary>
/// <param name="other"> The other SiloAddress to compare this one with. </param>
/// <returns> Returns <c>true</c> if the two SiloAddresses are considered to match -- if they are equal or if one generation or the other is 0. </returns>
internal bool Matches(SiloAddress other)
{
return other != null && Endpoint.Address.Equals(other.Endpoint.Address) && (Endpoint.Port == other.Endpoint.Port) &&
((Generation == other.Generation) || (Generation == 0) || (other.Generation == 0));
}
#region IEquatable<SiloAddress> Members
/// <summary> IEquatable.Equals method override. </summary>
public bool Equals(SiloAddress other)
{
return other != null && Endpoint.Address.Equals(other.Endpoint.Address) && (Endpoint.Port == other.Endpoint.Port) &&
((Generation == other.Generation));
}
#endregion
public int CompareTo(SiloAddress other)
{
if (other == null) return 1;
// Compare Generation first. It gives a cheap and fast way to compare, avoiding allocations
// and is also semantically meaningfull - older silos (with smaller Generation) will appear first in the comparison order.
// Only if Generations are the same, go on to compare Ports and IPAddress (which is more expansive to compare).
// Alternatively, we could compare ConsistentHashCode or UniformHashCode.
int comp = Generation.CompareTo(other.Generation);
if (comp != 0) return comp;
comp = Endpoint.Port.CompareTo(other.Endpoint.Port);
if (comp != 0) return comp;
return CompareIpAddresses(Endpoint.Address, other.Endpoint.Address);
}
// The comparions code is taken from: http://www.codeproject.com/Articles/26550/Extending-the-IPAddress-object-to-allow-relative-c
// Also note that this comparison does not handle semantic equivalence of IPv4 and IPv6 addresses.
// In particular, 127.0.0.1 and::1 are semanticaly the same, but not syntacticaly.
// For more information refer to: http://stackoverflow.com/questions/16618810/compare-ipv4-addresses-in-ipv6-notation
// and http://stackoverflow.com/questions/22187690/ip-address-class-getaddressbytes-method-putting-octets-in-odd-indices-of-the-byt
// and dual stack sockets, described at https://msdn.microsoft.com/en-us/library/system.net.ipaddress.maptoipv6(v=vs.110).aspx
private static int CompareIpAddresses(IPAddress one, IPAddress two)
{
int returnVal = 0;
if (one.AddressFamily == two.AddressFamily)
{
byte[] b1 = one.GetAddressBytes();
byte[] b2 = two.GetAddressBytes();
for (int i = 0; i < b1.Length; i++)
{
if (b1[i] < b2[i])
{
returnVal = -1;
break;
}
else if (b1[i] > b2[i])
{
returnVal = 1;
break;
}
}
}
else
{
returnVal = one.AddressFamily.CompareTo(two.AddressFamily);
}
return returnVal;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using TracerX.Viewer;
using System.Diagnostics;
using System.Linq;
namespace TracerX {
internal partial class CrumbBar : UserControl {
public CrumbBar() {
InitializeComponent();
_lastLinkLabel = linkLabel1;
_linkLabels.Add(linkLabel1);
_autoRepeatTimer.Tick += _autoRepeatTimer_Tick;
_autoRepeatTimer.Interval = 15;
_delayTimer.Tick += new EventHandler(_delayTimer_Tick);
_delayTimer.Interval = 100;
}
// Used to keep the crumb bar intact when the user navigates via the crumb bar.
private bool _keepCrumbBar;
// The _delayTimer is used to delay building the crumb bar for 100 milliseconds
// after a row is selected. This allows the user to scroll rapidly since we don't
// build the crumb bar for every row he scrolls over.
private Timer _delayTimer = new Timer();
// The currently selected Row. When the user selects a new row, this is set to the
// new row. If it does not change again in 100 milliseconds, the crumb bar is
// built for this row (_crumbBarRow will be set equal to _currentRow).
private Row _currentRow;
// The Row for which the crumb bar is currently built.
private Row _crumbBarRow;
// All Records from the log file.
private List<Record> _records;
// A list of LinkLabels because one LinkLabel can only have 31 links!
private List<LinkLabel> _linkLabels = new List<LinkLabel>();
// The last (rightmost) LinkLabel in _linkLabels;
private LinkLabel _lastLinkLabel;
// The linkLabel's scroll position is <= 0.
private int _scrollPos;
// Timer for repeated scrolling while mouse button is held down.
private Timer _autoRepeatTimer = new Timer();
// The LinkLabel controls must overlap to avoid visible gaps in the text.
private const int _overlap = 13;
// The most recently visited link;
private LinkLabel.Link _visited;
// The scroll amount is how many pixels to scroll per timer tick while the
// user holds the mouse button on the scroll button. It varies depending
// on the width of the LinkLabels.
int _scrollAmount = 6;
// Width in pixels of all LinkLabels laid out horizontally.
private int _scrollableWidth;
public void Clear() {
// We only keep linkLabel1 in _linkLabels and Controls.
_linkLabels.ForEach(ll => Controls.Remove(ll));
_linkLabels.Clear();
_linkLabels.Add(linkLabel1);
Controls.Add(linkLabel1);
_lastLinkLabel = linkLabel1;
linkLabel1.Links.Clear();
linkLabel1.Text = null;
_scrollPos = 0;
_visited = null;
}
// Called when the user selects or scrolls to a new Row.
public void SetCurrentRow(Row newRow, List<Record> records) {
// _keepCrumbBar means the user selected the row by clicking a link in the
// crumb bar. In that case, we just leave the crumb bar as-is.
if (!_keepCrumbBar) {
_currentRow = newRow;
_records = records;
_delayTimer.Stop();
_delayTimer.Start();
}
}
// Called when the _currentRow has been selected for 100 milliseconds.
private void _delayTimer_Tick(object sender, EventArgs e) {
_delayTimer.Stop();
BuildCrumbBar();
}
// Puts a list of links in the crumb bar, representing the current call stack.
// Only works with file version 5+ because Record.Caller is always null for
// earlier versions.
private void BuildCrumbBar() {
Clear();
_crumbBarRow = _currentRow;
if (_currentRow == null) return;
StringBuilder builder = new StringBuilder();
foreach (Record rec in GetCallStack(_currentRow)) {
AddToCrumbBar(builder, rec, 0);
}
// Now include the currently selected row.
AddToCrumbBar(builder, _currentRow.Rec, _currentRow.Line);
_lastLinkLabel.Text = builder.ToString();
_scrollableWidth = _lastLinkLabel.Right - linkLabel1.Left;
CrumbBar_Resize(null, null);
rightBtn.BringToFront();
leftBtn.BringToFront();
// Ensure the right end of the text is visible.
int rightEdge = rightBtn.Visible ? rightBtn.Left : this.Width;
if (_lastLinkLabel.Right > rightEdge) {
_scrollPos -= _lastLinkLabel.Right - rightEdge;
SetLocation();
}
// The wider the crumb bar, the faster it scrolls.
_scrollAmount = Math.Max(6, _scrollableWidth / 100);
//Debug.Print("_scrollAmount = " + _scrollAmount);
}
private void CrumbBar_Resize(object sender, EventArgs e) {
if (_lastLinkLabel == null) return;
var allWidth = _lastLinkLabel.Right - linkLabel1.Left;
if (allWidth > this.Width) {
leftBtn.Visible = true;
rightBtn.Visible = true;
// Don't allow any space between the LinkLabel and the right button.
if (rightBtn.Left > _lastLinkLabel.Right) _scrollPos += rightBtn.Left - _lastLinkLabel.Right;
} else {
leftBtn.Visible = false;
rightBtn.Visible = false;
_scrollPos = 0;
}
SetLocation();
}
// Sets the location of the LinkLabel based on _scrollPos.
private void SetLocation() {
if (leftBtn.Visible) linkLabel1.Left = _scrollPos + leftBtn.Right;
else linkLabel1.Left = _scrollPos;
leftBtn.Enabled = linkLabel1.Left < leftBtn.Right;
for (int i = 1; i < _linkLabels.Count; ++i) {
_linkLabels[i].Left = _linkLabels[i - 1].Right - _overlap;
}
rightBtn.Enabled = _lastLinkLabel.Right > rightBtn.Left;
}
// Adds a link to the crumbBar for the specified record. Adds appropriate text
// (method name or line number) to the StringBuilder. The lineNum parameter is
// only relevant if the Record is not a MethodEntry record.
private void AddToCrumbBar(StringBuilder builder, Record rec, int lineNum) {
string crumb;
if (rec.IsEntry) {
crumb = rec.MethodName.Name;
} else {
crumb = string.Format("Line {0}", rec.GetRecordNum(lineNum));
}
// If the current LinkLabel is full, assign it the text we have so far
// and make a new Linklabel for the "crumbs" we're about to add.
if (_lastLinkLabel.Links.Count == 30) {
_lastLinkLabel.Text = builder.ToString();
builder.Length = 0;
int loc = _lastLinkLabel.Right;
Color linkColor = _lastLinkLabel.LinkColor;
_lastLinkLabel = new LinkLabel();
_lastLinkLabel.Left = loc - _overlap;
_lastLinkLabel.AutoSize = true;
_lastLinkLabel.LinkClicked += linkLabel1_LinkClicked;
_lastLinkLabel.LinkColor = linkColor;
_linkLabels.Add(_lastLinkLabel);
Controls.Add(_lastLinkLabel);
_lastLinkLabel.BringToFront();
}
LinkLabel.Link link = new LinkLabel.Link(builder.Length, crumb.Length, rec);
link.Enabled = rec.IsVisible && rec != _crumbBarRow.Rec;
link.Name = "M"; // Anything but string.Empty.
_lastLinkLabel.Links.Add(link);
_visited = link;
builder.Append(crumb);
// We always add a separator arrow after each method (even the last one),
// which the user can click to get a list of methods called by the method.
if (rec.IsEntry) {
_lastLinkLabel.Links.Add(builder.Length + 1, 2, rec);
builder.Append(" -> ");
}
}
// Gets the call stack leading to the current record, not including the current record.
// All Records returned will be MethodEntry Records. Result is empty if CurrentRow is null or
// has no caller.
private List<Record> GetCallStack(Row origin) {
List<Record> result = new List<Record>();
if (origin != null) {
Record caller = origin.Rec.Caller;
while (caller != null) {
result.Add(caller);
caller = caller.Caller;
}
result.Reverse();
}
return result;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
if (e.Link.Name == string.Empty) {
ShowCalledMethodsForCrumbBarLink(e.Link);
} else {
SelectRowForCrumbBarLink(e.Link);
}
}
// Called when the user clicks an arrow in the crumbBar. This displays a
// list of methods called by the method to the left of the arrow. If the
// user selects one, we navigate to the the corresponding Record/Row in TheListView.
private void ShowCalledMethodsForCrumbBarLink(LinkLabel.Link clickedLink) {
Record methodRecord = (Record)clickedLink.LinkData;
MethodObject lastMethod = null;
int sequentialCount = 1;
ContextMenuStrip menu = new ContextMenuStrip();
ToolStripMenuItem menuItem = null;
// Scan records starting after the record whose called methods we want.
// Stop when we run out of records, reach the end of method whose called
// records we want (based on StackDepth), or put 30 items in the context menu.
for (int i = methodRecord.Index + 1;
i < _records.Count && menu.Items.Count < 30;
++i) //
{
if (_records[i].Thread == methodRecord.Thread) {
if (_records[i].StackDepth > methodRecord.StackDepth) {
if (_records[i].IsEntry && _records[i].Caller == methodRecord) {
if (_records[i].MethodName == lastMethod) {
// There may be many sequential calls to the same method. Instead of creating
// a MenuItem for each, count the calls and include the count in a single
// MenuItem's Text.
++sequentialCount;
} else {
if (sequentialCount > 1) {
menuItem.Text = string.Format("{0} ({1} calls)", lastMethod.Name, sequentialCount);
sequentialCount = 1;
}
lastMethod = _records[i].MethodName;
menuItem = new ToolStripMenuItem(lastMethod.Name, null, CrumbBarMenuItemClicked);
menuItem.Enabled = _records[i].IsVisible;
menuItem.Tag = _records[i];
menuItem.DisplayStyle = ToolStripItemDisplayStyle.Text;
menu.Items.Add(menuItem);
}
}
} else {
break;
}
} // Same thread.
}
if (sequentialCount > 1) {
menuItem.Text = string.Format("{0} ({1} calls)", lastMethod.Name, sequentialCount);
}
menu.ShowCheckMargin = false;
menu.ShowImageMargin = false;
menu.ShowItemToolTips = false;
if (menu.Items.Count == 0) {
//clickedLink.Enabled = false;
menuItem = new ToolStripMenuItem("No calls");
menuItem.Enabled = false;
menu.Items.Add(menuItem);
//linkLabel1.Text = linkLabel1.Text.Remove(clickedLink.Start);
linkLabel1.Links.Remove(clickedLink);
}
menu.Show(this, this.PointToClient(Control.MousePosition));
}
void CrumbBarMenuItemClicked(object sender, EventArgs e) {
ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
Record rec = (Record)menuItem.Tag;
MainForm.TheMainForm.SelectRowIndex(rec.RowIndices[0]);
}
// Called when the user clicks a method name in the crumbBar. This
// selects the corresponding Record/Row in TheListView.
private void SelectRowForCrumbBarLink(LinkLabel.Link clickedLink) {
try {
// Don't build a new crumbBar when we change the currently seleted row.
_keepCrumbBar = true;
// The stack origin (last entry in the stack, last link in the crumbBar) is
// special because that linkRecord may be a Record that is expanded into
// multiple Rows, and we need to select the right one of those Rows.
Record linkRecord = (Record)clickedLink.LinkData;
if (linkRecord == _crumbBarRow.Rec) {
MainForm.TheMainForm.SelectRowIndex(_crumbBarRow.Index);
} else {
MainForm.TheMainForm.SelectRowIndex(linkRecord.RowIndices[0]);
}
if (_visited != null) _visited.Enabled = true;
// Disable links for invisible records.
//foreach (LinkLabel.Link link in linkLabel1.Links) {
// linkRecord = link.LinkData as Record;
// if (linkRecord != null) link.Enabled = linkRecord.IsVisible;
//}
// Disable the link for the record we just selected.
clickedLink.Enabled = false;
_visited = clickedLink;
} finally {
_keepCrumbBar = false;
}
}
private void leftBtn_Paint(object sender, PaintEventArgs e) {
// Draw a triangle pointing to the left.
Brush brush = leftBtn.Enabled ? Brushes.Black : Brushes.DarkGray;
const int margin = 3;
Point p1 = new Point(leftBtn.Width - margin, margin);
Point p2 = new Point(leftBtn.Width - margin, leftBtn.Height - margin);
Point p3 = new Point(margin, leftBtn.Height / 2);
Point[] points = new Point[] { p1, p2, p3 };
e.Graphics.FillPolygon(brush, points);
}
private void rightBtn_Paint(object sender, PaintEventArgs e) {
// Draw a triangle pointing to the right.
Brush brush = rightBtn.Enabled ? Brushes.Black : Brushes.DarkGray;
const int margin = 3;
Point p1 = new Point(margin, margin);
Point p2 = new Point(margin, rightBtn.Height - margin);
Point p3 = new Point(rightBtn.Width - margin, rightBtn.Height / 2);
Point[] points = new Point[] { p1, p2, p3 };
e.Graphics.FillPolygon(brush, points);
}
// Handler for BOTH buttons.
private void leftBtn_EnabledChanged(object sender, EventArgs e) {
// Cause the changed button to be repainted.
if (sender == leftBtn) leftBtn.Invalidate();
else rightBtn.Invalidate();
if (!((Button)sender).Enabled) _autoRepeatTimer.Stop();
}
// MouseDown handler for BOTH buttons.
// Starts a Timer to scroll repeatedly while mouse button is down.
private void Btn_MouseDown(object sender, MouseEventArgs e) {
Debug.Print("Down");
// Set the Tag to the button so the Tick handler knows which direction to scroll.
_autoRepeatTimer.Tag = sender;
_autoRepeatTimer.Start();
}
// MouseUp handler for BOTH buttons.
private void Btn_MouseUp(object sender, MouseEventArgs e) {
Debug.Print("Up");
_autoRepeatTimer.Stop();
}
void _autoRepeatTimer_Tick(object sender, EventArgs e) {
Debug.Print("Tick");
Button btn = (Button)_autoRepeatTimer.Tag;
// If the mouse button is still down on the scroll button, scroll.
if (btn.RectangleToScreen(btn.ClientRectangle).Contains(Control.MousePosition)) {
if (btn.Enabled) {
if (btn == leftBtn) {
int delta = Math.Min(_scrollAmount, leftBtn.Right - linkLabel1.Left);
_scrollPos += delta;
} else {
int delta = Math.Min(_scrollAmount, _lastLinkLabel.Right - rightBtn.Left);
_scrollPos -= delta;
}
SetLocation();
}
} else {
_autoRepeatTimer.Stop();
}
}
}
}
| |
// 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.TypeSystem.Ecma;
using Internal.IL.Stubs;
using Debug = System.Diagnostics.Debug;
namespace Internal.IL
{
internal sealed class ILProvider : LockFreeReaderHashtable<MethodDesc, ILProvider.MethodILData>
{
private PInvokeILProvider _pinvokeILProvider;
public ILProvider(PInvokeILProvider pinvokeILProvider)
{
_pinvokeILProvider = pinvokeILProvider;
}
private MethodIL TryGetRuntimeImplementedMethodIL(MethodDesc method)
{
// Provides method bodies for runtime implemented methods. It can return null for
// methods that are treated specially by the codegen.
Debug.Assert(method.IsRuntimeImplemented);
TypeDesc owningType = method.OwningType;
if (owningType.IsDelegate)
{
return DelegateMethodILEmitter.EmitIL(method);
}
return null;
}
/// <summary>
/// Provides method bodies for intrinsics recognized by the compiler.
/// It can return null if it's not an intrinsic recognized by the compiler,
/// but an intrinsic e.g. recognized by codegen.
/// </summary>
private MethodIL TryGetIntrinsicMethodIL(MethodDesc method)
{
Debug.Assert(method.IsIntrinsic);
MetadataType owningType = method.OwningType as MetadataType;
if (owningType == null)
return null;
switch (owningType.Name)
{
case "Unsafe":
{
if (owningType.Namespace == "Internal.Runtime.CompilerServices")
return UnsafeIntrinsics.EmitIL(method);
}
break;
case "Debug":
{
if (owningType.Namespace == "System.Diagnostics" && method.Name == "DebugBreak")
return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.break_, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null);
}
break;
case "EETypePtr":
{
if (owningType.Namespace == "System" && method.Name == "EETypePtrOf")
return EETypePtrOfIntrinsic.EmitIL(method);
}
break;
case "RuntimeAugments":
{
if (owningType.Namespace == "Internal.Runtime.Augments" && method.Name == "GetCanonType")
return GetCanonTypeIntrinsic.EmitIL(method);
}
break;
}
return null;
}
/// <summary>
/// Provides method bodies for intrinsics recognized by the compiler that
/// are specialized per instantiation. It can return null if the intrinsic
/// is not recognized.
/// </summary>
private MethodIL TryGetPerInstantiationIntrinsicMethodIL(MethodDesc method)
{
Debug.Assert(method.IsIntrinsic);
MetadataType owningType = method.OwningType.GetTypeDefinition() as MetadataType;
if (owningType == null)
return null;
string methodName = method.Name;
switch (owningType.Name)
{
case "RuntimeHelpers":
{
if ((methodName == "IsReferenceOrContainsReferences" || methodName == "IsReference")
&& owningType.Namespace == "System.Runtime.CompilerServices")
{
TypeDesc elementType = method.Instantiation[0];
// Fallback to non-intrinsic implementation for universal generics
if (elementType.IsCanonicalSubtype(CanonicalFormKind.Universal))
return null;
bool result = elementType.IsGCPointer;
if (methodName == "IsReferenceOrContainsReferences")
{
result |= (elementType.IsDefType ? ((DefType)elementType).ContainsGCPointers : false);
}
return new ILStubMethodIL(method, new byte[] {
result ? (byte)ILOpcode.ldc_i4_1 : (byte)ILOpcode.ldc_i4_0,
(byte)ILOpcode.ret },
Array.Empty<LocalVariableDefinition>(), null);
}
}
break;
case "Comparer`1":
{
if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic")
return ComparerIntrinsics.EmitComparerCreate(method);
}
break;
case "EqualityComparer`1":
{
if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic")
return ComparerIntrinsics.EmitEqualityComparerCreate(method);
}
break;
case "EqualityComparerHelpers":
{
if (owningType.Namespace != "Internal.IntrinsicSupport")
return null;
if (methodName == "EnumOnlyEquals")
{
// EnumOnlyEquals would basically like to do this:
// static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x == y;
// This is not legal though.
// We don't want to do this:
// static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x.Equals(y);
// Because it would box y.
// So we resort to some per-instantiation magic.
TypeDesc elementType = method.Instantiation[0];
if (!elementType.IsEnum)
return null;
ILOpcode convInstruction;
if (((DefType)elementType).InstanceFieldSize.AsInt <= 4)
{
convInstruction = ILOpcode.conv_i4;
}
else
{
Debug.Assert(((DefType)elementType).InstanceFieldSize.AsInt == 8);
convInstruction = ILOpcode.conv_i8;
}
return new ILStubMethodIL(method, new byte[] {
(byte)ILOpcode.ldarg_0,
(byte)convInstruction,
(byte)ILOpcode.ldarg_1,
(byte)convInstruction,
(byte)ILOpcode.prefix1, unchecked((byte)ILOpcode.ceq),
(byte)ILOpcode.ret,
},
Array.Empty<LocalVariableDefinition>(), null);
}
else if (methodName == "GetComparerForReferenceTypesOnly")
{
TypeDesc elementType = method.Instantiation[0];
if (!elementType.IsRuntimeDeterminedSubtype
&& !elementType.IsCanonicalSubtype(CanonicalFormKind.Any)
&& !elementType.IsGCPointer)
{
return new ILStubMethodIL(method, new byte[] {
(byte)ILOpcode.ldnull,
(byte)ILOpcode.ret
},
Array.Empty<LocalVariableDefinition>(), null);
}
}
else if (methodName == "StructOnlyEquals")
{
TypeDesc elementType = method.Instantiation[0];
if (!elementType.IsRuntimeDeterminedSubtype
&& !elementType.IsCanonicalSubtype(CanonicalFormKind.Any)
&& !elementType.IsGCPointer)
{
Debug.Assert(elementType.IsValueType);
TypeSystemContext context = elementType.Context;
MetadataType helperType = context.SystemModule.GetKnownType("Internal.IntrinsicSupport", "EqualityComparerHelpers");
MethodDesc methodToCall = null;
if (elementType.IsEnum)
{
methodToCall = helperType.GetKnownMethod("EnumOnlyEquals", null).MakeInstantiatedMethod(elementType);
}
else if (elementType.IsNullable && ComparerIntrinsics.ImplementsIEquatable(elementType.Instantiation[0]))
{
methodToCall = helperType.GetKnownMethod("StructOnlyEqualsNullable", null).MakeInstantiatedMethod(elementType.Instantiation[0]);
}
else if (ComparerIntrinsics.ImplementsIEquatable(elementType))
{
methodToCall = helperType.GetKnownMethod("StructOnlyEqualsIEquatable", null).MakeInstantiatedMethod(elementType);
}
if (methodToCall != null)
{
return new ILStubMethodIL(method, new byte[]
{
(byte)ILOpcode.ldarg_0,
(byte)ILOpcode.ldarg_1,
(byte)ILOpcode.call, 1, 0, 0, 0,
(byte)ILOpcode.ret
},
Array.Empty<LocalVariableDefinition>(), new object[] { methodToCall });
}
}
}
}
break;
}
return null;
}
private MethodIL CreateMethodIL(MethodDesc method)
{
if (method is EcmaMethod)
{
// TODO: Workaround: we should special case methods with Intrinsic attribute, but since
// CoreLib source is still not in the repo, we have to work with what we have, which is
// an MCG attribute on the type itself...
if (((MetadataType)method.OwningType).HasCustomAttribute("System.Runtime.InteropServices", "McgIntrinsicsAttribute"))
{
var name = method.Name;
if (name == "Call")
{
return CalliIntrinsic.EmitIL(method);
}
else
if (name == "AddrOf")
{
return AddrOfIntrinsic.EmitIL(method);
}
}
if (method.IsIntrinsic)
{
MethodIL result = TryGetIntrinsicMethodIL(method);
if (result != null)
return result;
}
if (method.IsPInvoke)
{
var pregenerated = McgInteropSupport.TryGetPregeneratedPInvoke(method);
if (pregenerated == null)
return _pinvokeILProvider.EmitIL(method);
method = pregenerated;
}
if (method.IsRuntimeImplemented)
{
MethodIL result = TryGetRuntimeImplementedMethodIL(method);
if (result != null)
return result;
}
MethodIL methodIL = EcmaMethodIL.Create((EcmaMethod)method);
if (methodIL != null)
return methodIL;
return null;
}
else
if (method is MethodForInstantiatedType || method is InstantiatedMethod)
{
// Intrinsics specialized per instantiation
if (method.IsIntrinsic)
{
MethodIL methodIL = TryGetPerInstantiationIntrinsicMethodIL(method);
if (methodIL != null)
return methodIL;
}
var methodDefinitionIL = GetMethodIL(method.GetTypicalMethodDefinition());
if (methodDefinitionIL == null)
return null;
return new InstantiatedMethodIL(method, methodDefinitionIL);
}
else
if (method is ILStubMethod)
{
return ((ILStubMethod)method).EmitIL();
}
else
if (method is ArrayMethod)
{
return ArrayMethodILEmitter.EmitIL((ArrayMethod)method);
}
else
{
Debug.Assert(!(method is PInvokeTargetNativeMethod), "Who is asking for IL of PInvokeTargetNativeMethod?");
return null;
}
}
internal class MethodILData
{
public MethodDesc Method;
public MethodIL MethodIL;
}
protected override int GetKeyHashCode(MethodDesc key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(MethodILData value)
{
return value.Method.GetHashCode();
}
protected override bool CompareKeyToValue(MethodDesc key, MethodILData value)
{
return Object.ReferenceEquals(key, value.Method);
}
protected override bool CompareValueToValue(MethodILData value1, MethodILData value2)
{
return Object.ReferenceEquals(value1.Method, value2.Method);
}
protected override MethodILData CreateValueFromKey(MethodDesc key)
{
return new MethodILData() { Method = key, MethodIL = CreateMethodIL(key) };
}
public MethodIL GetMethodIL(MethodDesc method)
{
return GetOrCreateValue(method).MethodIL;
}
}
}
| |
/*
Copyright (c) 2006- DEVSENSE
Copyright (c) 2004-2006 Tomas Matousek, Vaclav Novak and Martin Maly.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using PHP.Core.Parsers;
namespace PHP.Core.AST
{
#region IncludingEx
/// <summary>
/// Inclusion expression (include, require, synthetic auto-inclusion nodes).
/// </summary>
[Serializable]
public sealed class IncludingEx : Expression
{
public override Operations Operation { get { return Operations.Inclusion; } }
/// <summary>
/// An argument of the inclusion.
/// </summary>
public Expression/*!*/ Target { get { return fileNameEx; } set { fileNameEx = value; } }
private Expression/*!*/ fileNameEx;
/// <summary>
/// A type of an inclusion (include, include-once, ...).
/// </summary>
public InclusionTypes InclusionType { get { return inclusionType; } }
private InclusionTypes inclusionType;
/// <summary>
/// Whether the inclusion is conditional.
/// </summary>
public bool IsConditional { get { return isConditional; } }
private bool isConditional;
public Scope Scope { get { return scope; } }
private Scope scope;
public SourceUnit/*!*/ SourceUnit { get { return sourceUnit; } }
private SourceUnit/*!*/ sourceUnit;
public IncludingEx(SourceUnit/*!*/ sourceUnit, Scope scope, bool isConditional, Text.Span span,
InclusionTypes inclusionType, Expression/*!*/ fileName)
: base(span)
{
Debug.Assert(fileName != null);
this.inclusionType = inclusionType;
this.fileNameEx = fileName;
this.scope = scope;
this.isConditional = isConditional;
this.sourceUnit = sourceUnit;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitIncludingEx(this);
}
}
#endregion
#region IssetEx
/// <summary>
/// Represents <c>isset</c> construct.
/// </summary>
[Serializable]
public sealed class IssetEx : Expression
{
public override Operations Operation { get { return Operations.Isset; } }
private readonly List<VariableUse>/*!*/ varList;
/// <summary>List of variables to test</summary>
public List<VariableUse>/*!*/ VarList { get { return varList; } }
public IssetEx(Text.Span span, List<VariableUse>/*!*/ varList)
: base(span)
{
Debug.Assert(varList != null && varList.Count > 0);
this.varList = varList;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitIssetEx(this);
}
}
#endregion
#region EmptyEx
/// <summary>
/// Represents <c>empty</c> construct.
/// </summary>
[Serializable]
public sealed class EmptyEx : Expression
{
public override Operations Operation { get { return Operations.Empty; } }
/// <summary>
/// Expression to be checked for emptiness.
/// </summary>
public Expression/*!*/Expression { get { return this.expression; } set { this.expression = value; } }
private Expression/*!*/expression;
public EmptyEx(Text.Span p, Expression expression)
: base(p)
{
if (expression == null)
throw new ArgumentNullException("expression");
this.expression = expression;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitEmptyEx(this);
}
}
#endregion
#region EvalEx, AssertEx
/// <summary>
/// Represents <c>eval</c> construct.
/// </summary>
[Serializable]
public sealed class EvalEx : Expression
{
public override Operations Operation { get { return Operations.Eval; } }
/// <summary>Expression containing source code to be evaluated.</summary>
public Expression /*!*/ Code { get { return code; } set { code = value; } }
/// <summary>
/// Expression containing source code to be evaluated.
/// </summary>
private Expression/*!*/ code;
#region Construction
/// <summary>
/// Creates a node representing an eval or assert constructs.
/// </summary>
/// <param name="span">Position.</param>
/// <param name="code">Source code expression.</param>
public EvalEx(Text.Span span, Expression/*!*/ code)
: base(span)
{
this.code = code;
}
#endregion
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitEvalEx(this);
}
}
/// <summary>
/// Meta language element used for assert() function call analysis.
/// </summary>
[Serializable]
internal sealed class AssertEx : Expression
{
public override Operations Operation { get { return Operations.Eval; } }
/// <summary>Expression containing source code to be evaluated.</summary>
public Expression /*!*/ CodeEx { get; internal set; }
///// <summary>Description para,eter.</summary>
//public Expression DescriptionEx { get; internal set; }
public AssertEx(Text.Span span, CallSignature callsignature)
: base(span)
{
Debug.Assert(callsignature.Parameters.Any());
Debug.Assert(callsignature.GenericParams.Empty());
this.CodeEx = callsignature.Parameters[0].Expression;
//this.DescriptionEx = description;
}
public override void VisitMe(TreeVisitor visitor)
{
// note: should not be used
visitor.VisitElement(this.CodeEx);
//visitor.VisitElement(this.DescriptionEx);
}
}
#endregion
#region ExitEx
/// <summary>
/// Represents <c>exit</c> expression.
/// </summary>
[Serializable]
public sealed class ExitEx : Expression
{
public override Operations Operation { get { return Operations.Exit; } }
/// <summary>Die (exit) expression. Can be null.</summary>
public Expression ResulExpr { get { return resultExpr; } set { resultExpr = value; } }
private Expression resultExpr; //can be null
public ExitEx(Text.Span span, Expression resultExpr)
: base(span)
{
this.resultExpr = resultExpr;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitExitEx(this);
}
}
#endregion
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Signum.Engine;
using Signum.Engine.Maps;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Signum.React.Json
{
public class MListJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IMListPrivate).IsAssignableFrom(objectType);
}
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
giWriteJsonInternal.GetInvoker(value!.GetType().ElementType()!)(writer, (IMListPrivate)value, serializer);
}
static GenericInvoker<Action<JsonWriter, IMListPrivate, JsonSerializer>> giWriteJsonInternal = new GenericInvoker<Action<JsonWriter, IMListPrivate, JsonSerializer>>(
(writer, value, serializer) => WriteJsonInternal<int>(writer, (MList<int>)value, serializer));
static void WriteJsonInternal<T>(JsonWriter writer, MList<T> value, JsonSerializer serializer)
{
var errors = new List<string>();
serializer.Error += delegate (object? sender, ErrorEventArgs args)
{
// only log an error once
if (args.CurrentObject == args.ErrorContext.OriginalObject)
{
errors.Add(args.ErrorContext.Error.Message);
}
};
writer.WriteStartArray();
var tup = JsonSerializerExtensions.CurrentPropertyRouteAndEntity!.Value;
var elementPr = tup.pr.Add("Item");
using (JsonSerializerExtensions.SetCurrentPropertyRouteAndEntity((elementPr, tup.mod)))
{
foreach (var item in ((IMListPrivate<T>)value).InnerList)
{
writer.WriteStartObject();
writer.WritePropertyName("rowId");
writer.WriteValue(item.RowId?.Object);
writer.WritePropertyName("element");
serializer.Serialize(writer, item.Element);
writer.WriteEndObject();
}
}
if (errors.Any())
throw new JsonSerializationException(errors.ToString("\r\n"));
writer.WriteEndArray();
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
return giReadJsonInternal.GetInvoker(objectType.ElementType()!)(reader, (IMListPrivate)existingValue!, serializer);
}
static GenericInvoker<Func<JsonReader, IMListPrivate, JsonSerializer, IMListPrivate>> giReadJsonInternal =
new GenericInvoker<Func<JsonReader, IMListPrivate, JsonSerializer, IMListPrivate>>(
(reader, value, serializer) => ReadJsonInternal<int>(reader, (IMListPrivate<int>)value, serializer));
static MList<T> ReadJsonInternal<T>(JsonReader reader, IMListPrivate<T> existingValue, JsonSerializer serializer)
{
var errors = new List<string>();
serializer.Error += delegate (object? sender, ErrorEventArgs args)
{
// only log an error once
if (args.CurrentObject == args.ErrorContext.OriginalObject)
{
errors.Add(args.ErrorContext.Error.Message);
}
};
var dic = existingValue == null ? new Dictionary<PrimaryKey, MList<T>.RowIdElement>() :
existingValue.InnerList.Where(a => a.RowId.HasValue).ToDictionary(a => a.RowId!.Value, a => a);
var newList = new List<MList<T>.RowIdElement>();
var tup = JsonSerializerExtensions.CurrentPropertyRouteAndEntity!.Value;
var elementPr = tup.pr.Add("Item");
var rowIdType = GetRowIdTypeFromAttribute(tup.pr);
reader.Assert(JsonToken.StartArray);
reader.Read();
using (JsonSerializerExtensions.SetCurrentPropertyRouteAndEntity((elementPr, tup.mod)))
{
while (reader.TokenType == JsonToken.StartObject)
{
reader.Read();
reader.Assert(JsonToken.PropertyName);
if (((string)reader.Value!) != "rowId")
throw new JsonSerializationException($"member 'rowId' expected in {reader.Path}");
reader.Read();
var rowIdValue = reader.Value;
reader.Read();
reader.Assert(JsonToken.PropertyName);
if (((string)reader.Value!) != "element")
throw new JsonSerializationException($"member 'element' expected in {reader.Path}");
reader.Read();
if (rowIdValue != null && !rowIdValue.Equals(GraphExplorer.DummyRowId.Object))
{
var rowId = new PrimaryKey((IComparable)ReflectionTools.ChangeType(rowIdValue, rowIdType)!);
var oldValue = dic.TryGetS(rowId);
if (oldValue == null)
{
T newValue = (T)serializer.DeserializeValue(reader, typeof(T), null)!;
newList.Add(new MList<T>.RowIdElement(newValue, rowId, null));
}
else
{
T newValue = (T)serializer.DeserializeValue(reader, typeof(T), oldValue.Value.Element)!;
if (oldValue.Value.Element!.Equals(newValue))
newList.Add(new MList<T>.RowIdElement(newValue, rowId, oldValue.Value.OldIndex));
else
newList.Add(new MList<T>.RowIdElement(newValue));
}
}
else
{
var newValue = (T)serializer.DeserializeValue(reader, typeof(T), null)!;
newList.Add(new MList<T>.RowIdElement(newValue));
}
if (errors.Any())
throw new JsonSerializationException(errors.ToString("\r\n"));
reader.Read();
reader.Assert(JsonToken.EndObject);
reader.Read();
}
}
reader.Assert(JsonToken.EndArray);
if (existingValue == null) //Strange case...
{
if (newList.IsEmpty())
return null!;
else
existingValue = new MList<T>();
}
bool orderMatters = GetPreserveOrderFromAttribute(tup.pr);
if (!existingValue.IsEqualTo(newList, orderMatters))
{
if (!JsonSerializerExtensions.AllowDirectMListChanges)
return new MList<T>(newList);
EntityJsonConverter.AssertCanWrite(tup.pr, tup.mod);
existingValue.AssignMList(newList);
}
return (MList<T>)existingValue;
}
private static Type GetRowIdTypeFromAttribute(PropertyRoute route)
{
var settings = Schema.Current.Settings;
var att = settings.FieldAttribute<PrimaryKeyAttribute>(route) ??
(route.IsVirtualMList() ? settings.TypeAttribute<PrimaryKeyAttribute>(route.Type.ElementType()!) : null) ??
settings.DefaultPrimaryKeyAttribute;
return att.Type;
}
private static bool GetPreserveOrderFromAttribute(PropertyRoute route)
{
var att = Schema.Current.Settings.FieldAttribute<PreserveOrderAttribute>(route);
return att!=null;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ExportJobsOperationResultsOperations operations.
/// </summary>
internal partial class ExportJobsOperationResultsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IExportJobsOperationResultsOperations
{
/// <summary>
/// Initializes a new instance of the ExportJobsOperationResultsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExportJobsOperationResultsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Fetches the result of the operation triggered by the Export Job API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='operationId'>
/// OperationID which represents the export job.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<OperationResultInfoBaseResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (operationId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("operationId", operationId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/operationResults/{operationId}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<OperationResultInfoBaseResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationResultInfoBaseResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using LinFx.Domain.Entities;
using LinFx.Extensions.Data;
using LinFx.Extensions.DependencyInjection;
using LinFx.Extensions.ExceptionHandling;
using LinFx.Extensions.ExceptionHandling.Localization;
using LinFx.Extensions.Http;
using LinFx.Extensions.Http.Client;
using LinFx.Extensions.Validation;
using LinFx.Security.Authorization;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinFx.Extensions.AspNetCore.ExceptionHandling;
public class DefaultExceptionToErrorInfoConverter : IExceptionToErrorInfoConverter, ITransientDependency
{
protected ExceptionLocalizationOptions LocalizationOptions { get; }
protected IStringLocalizerFactory StringLocalizerFactory { get; }
protected IStringLocalizer<ExceptionHandlingResource> L { get; }
protected IServiceProvider ServiceProvider { get; }
public DefaultExceptionToErrorInfoConverter(
IOptions<ExceptionLocalizationOptions> localizationOptions,
IStringLocalizerFactory stringLocalizerFactory,
IStringLocalizer<ExceptionHandlingResource> stringLocalizer,
IServiceProvider serviceProvider)
{
ServiceProvider = serviceProvider;
StringLocalizerFactory = stringLocalizerFactory;
L = stringLocalizer;
LocalizationOptions = localizationOptions.Value;
}
public RemoteServiceErrorInfo Convert(Exception exception, bool includeSensitiveDetails)
{
var exceptionHandlingOptions = CreateDefaultOptions();
exceptionHandlingOptions.SendExceptionsDetailsToClients = includeSensitiveDetails;
exceptionHandlingOptions.SendStackTraceToClients = includeSensitiveDetails;
var errorInfo = CreateErrorInfoWithoutCode(exception, exceptionHandlingOptions);
if (exception is IHasErrorCode hasErrorCodeException)
errorInfo.Code = hasErrorCodeException.Code;
return errorInfo;
}
public RemoteServiceErrorInfo Convert(Exception exception, Action<ExceptionHandlingOptions> options = null)
{
var exceptionHandlingOptions = CreateDefaultOptions();
options?.Invoke(exceptionHandlingOptions);
var errorInfo = CreateErrorInfoWithoutCode(exception, exceptionHandlingOptions);
if (exception is IHasErrorCode hasErrorCodeException)
errorInfo.Code = hasErrorCodeException.Code;
return errorInfo;
}
protected virtual RemoteServiceErrorInfo CreateErrorInfoWithoutCode(Exception exception, ExceptionHandlingOptions options)
{
if (options.SendExceptionsDetailsToClients)
return CreateDetailedErrorInfoFromException(exception, options.SendStackTraceToClients);
exception = TryToGetActualException(exception);
if (exception is RemoteCallException remoteCallException && remoteCallException.Error != null)
return remoteCallException.Error;
if (exception is DbConcurrencyException)
return new RemoteServiceErrorInfo(L["DbConcurrencyErrorMessage"]);
if (exception is EntityNotFoundException)
return CreateEntityNotFoundError(exception as EntityNotFoundException);
var errorInfo = new RemoteServiceErrorInfo();
if (exception is UserFriendlyException || exception is RemoteCallException)
{
errorInfo.Message = exception.Message;
errorInfo.Details = (exception as IHasErrorDetails)?.Details;
}
if (exception is IHasValidationErrors)
{
if (errorInfo.Message.IsNullOrEmpty())
errorInfo.Message = L["ValidationErrorMessage"];
if (errorInfo.Details.IsNullOrEmpty())
errorInfo.Details = GetValidationErrorNarrative(exception as IHasValidationErrors);
errorInfo.ValidationErrors = GetValidationErrorInfos(exception as IHasValidationErrors);
}
TryToLocalizeExceptionMessage(exception, errorInfo);
if (errorInfo.Message.IsNullOrEmpty())
errorInfo.Message = L["InternalServerErrorMessage"];
errorInfo.Data = exception.Data;
return errorInfo;
}
protected virtual void TryToLocalizeExceptionMessage(Exception exception, RemoteServiceErrorInfo errorInfo)
{
//if (exception is ILocalizeErrorMessage localizeErrorMessageException)
//{
// using (var scope = ServiceProvider.CreateScope())
// {
// errorInfo.Message = localizeErrorMessageException.LocalizeMessage(new LocalizationContext(scope.ServiceProvider));
// }
// return;
//}
if (!(exception is IHasErrorCode exceptionWithErrorCode))
return;
if (exceptionWithErrorCode.Code.IsNullOrWhiteSpace() ||
!exceptionWithErrorCode.Code.Contains(":"))
return;
var codeNamespace = exceptionWithErrorCode.Code.Split(':')[0];
var localizationResourceType = LocalizationOptions.ErrorCodeNamespaceMappings.GetOrDefault(codeNamespace);
if (localizationResourceType == null)
return;
var stringLocalizer = StringLocalizerFactory.Create(localizationResourceType);
var localizedString = stringLocalizer[exceptionWithErrorCode.Code];
if (localizedString.ResourceNotFound)
return;
var localizedValue = localizedString.Value;
if (exception.Data != null && exception.Data.Count > 0)
{
foreach (var key in exception.Data.Keys)
{
localizedValue = localizedValue.Replace("{" + key + "}", exception.Data[key]?.ToString());
}
}
errorInfo.Message = localizedValue;
}
protected virtual RemoteServiceErrorInfo CreateEntityNotFoundError(EntityNotFoundException exception)
{
if (exception.EntityType != null)
{
return new RemoteServiceErrorInfo(
string.Format(
L["EntityNotFoundErrorMessage"],
exception.EntityType.Name,
exception.Id
)
);
}
return new RemoteServiceErrorInfo(exception.Message);
}
protected virtual Exception TryToGetActualException(Exception exception)
{
if (exception is AggregateException && exception.InnerException != null)
{
var aggException = exception as AggregateException;
if (aggException.InnerException is ValidationException ||
aggException.InnerException is AuthorizationException ||
aggException.InnerException is EntityNotFoundException ||
aggException.InnerException is IBusinessException)
{
return aggException.InnerException;
}
}
return exception;
}
protected virtual RemoteServiceErrorInfo CreateDetailedErrorInfoFromException(Exception exception, bool sendStackTraceToClients)
{
var detailBuilder = new StringBuilder();
AddExceptionToDetails(exception, detailBuilder, sendStackTraceToClients);
var errorInfo = new RemoteServiceErrorInfo(exception.Message, detailBuilder.ToString());
if (exception is ValidationException)
errorInfo.ValidationErrors = GetValidationErrorInfos(exception as ValidationException);
return errorInfo;
}
protected virtual void AddExceptionToDetails(Exception exception, StringBuilder detailBuilder, bool sendStackTraceToClients)
{
//Exception Message
detailBuilder.AppendLine(exception.GetType().Name + ": " + exception.Message);
//Additional info for UserFriendlyException
//if (exception is IUserFriendlyException &&
// exception is IHasErrorDetails)
//{
// var details = ((IHasErrorDetails)exception).Details;
// if (!details.IsNullOrEmpty())
// {
// detailBuilder.AppendLine(details);
// }
//}
//Additional info for ValidationException
if (exception is ValidationException)
{
var validationException = exception as ValidationException;
if (validationException.ValidationErrors.Count > 0)
{
detailBuilder.AppendLine(GetValidationErrorNarrative(validationException));
}
}
//Exception StackTrace
if (sendStackTraceToClients && !string.IsNullOrEmpty(exception.StackTrace))
{
detailBuilder.AppendLine("STACK TRACE: " + exception.StackTrace);
}
//Inner exception
if (exception.InnerException != null)
{
AddExceptionToDetails(exception.InnerException, detailBuilder, sendStackTraceToClients);
}
//Inner exceptions for AggregateException
if (exception is AggregateException)
{
var aggException = exception as AggregateException;
if (aggException.InnerExceptions.IsNullOrEmpty())
return;
foreach (var innerException in aggException.InnerExceptions)
{
AddExceptionToDetails(innerException, detailBuilder, sendStackTraceToClients);
}
}
}
protected virtual RemoteServiceValidationErrorInfo[] GetValidationErrorInfos(IHasValidationErrors validationException)
{
var validationErrorInfos = new List<RemoteServiceValidationErrorInfo>();
foreach (var validationResult in validationException.ValidationErrors)
{
var validationError = new RemoteServiceValidationErrorInfo(validationResult.ErrorMessage);
if (validationResult.MemberNames != null && validationResult.MemberNames.Any())
{
validationError.Members = validationResult.MemberNames.Select(m => m.ToCamelCase()).ToArray();
}
validationErrorInfos.Add(validationError);
}
return validationErrorInfos.ToArray();
}
protected virtual string GetValidationErrorNarrative(IHasValidationErrors validationException)
{
var detailBuilder = new StringBuilder();
detailBuilder.AppendLine(L["ValidationNarrativeErrorMessageTitle"]);
foreach (var validationResult in validationException.ValidationErrors)
{
detailBuilder.AppendFormat(" - {0}", validationResult.ErrorMessage);
detailBuilder.AppendLine();
}
return detailBuilder.ToString();
}
protected virtual ExceptionHandlingOptions CreateDefaultOptions()
{
return new ExceptionHandlingOptions
{
SendExceptionsDetailsToClients = false,
SendStackTraceToClients = true
};
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
#if NETFRAMEWORK
using System;
using System.Threading;
using System.Diagnostics;
using NUnit.Common;
using NUnit.Engine.Internal;
using NUnit.Engine.Communication.Transports.Remoting;
using NUnit.Engine.Communication.Transports.Tcp;
namespace NUnit.Engine.Services
{
/// <summary>
/// The TestAgency class provides RemoteTestAgents
/// on request and tracks their status. Agents
/// are wrapped in an instance of the TestAgent
/// class. Multiple agent types are supported
/// but only one, ProcessAgent is implemented
/// at this time.
/// </summary>
public partial class TestAgency : ITestAgency, IService
{
private static readonly Logger log = InternalTrace.GetLogger(typeof(TestAgency));
private const int NORMAL_TIMEOUT = 30000; // 30 seconds
private const int DEBUG_TIMEOUT = NORMAL_TIMEOUT * 10; // 5 minutes
private readonly AgentStore _agentStore = new AgentStore();
private IRuntimeFrameworkService _runtimeService;
private IAvailableRuntimes _availableRuntimeService;
// Transports used for various target runtimes
private TestAgencyRemotingTransport _remotingTransport; // .NET Framework
private TestAgencyTcpTransport _tcpTransport; // .NET Standard 2.0
internal virtual string RemotingUrl => _remotingTransport.ServerUrl;
internal virtual string TcpEndPoint => _tcpTransport.ServerUrl;
public TestAgency()
{
var uri = "TestAgency-" + Guid.NewGuid();
var port = 0;
_remotingTransport = new TestAgencyRemotingTransport(this, uri, port);
_tcpTransport = new TestAgencyTcpTransport(this, port);
}
public void Register(ITestAgent agent)
{
_agentStore.Register(agent);
}
public ITestAgent GetAgent(TestPackage package)
{
// Target Runtime must be specified by this point
string runtimeSetting = package.GetSetting(EnginePackageSettings.TargetRuntimeFramework, "");
Guard.OperationValid(runtimeSetting.Length > 0, "LaunchAgentProcess called with no runtime specified");
// If target runtime is not available, something went wrong earlier.
// We list all available frameworks to use in debugging.
var targetRuntime = RuntimeFramework.Parse(runtimeSetting);
if (!_runtimeService.IsAvailable(targetRuntime.Id))
{
string msg = $"The {targetRuntime} framework is not available.\r\nAvailable frameworks:";
foreach (var runtime in _availableRuntimeService.AvailableRuntimes)
msg += $" {runtime}";
throw new ArgumentException(msg);
}
var agentId = Guid.NewGuid();
var agentProcess = new AgentProcess(this, package, agentId);
agentProcess.Exited += (sender, e) => OnAgentExit((Process)sender, agentId);
agentProcess.Start();
log.Debug("Launched Agent process {0} - see nunit-agent_{0}.log", agentProcess.Id);
log.Debug("Command line: \"{0}\" {1}", agentProcess.StartInfo.FileName, agentProcess.StartInfo.Arguments);
_agentStore.AddAgent(agentId, agentProcess);
log.Debug($"Waiting for agent {agentId:B} to register");
const int pollTime = 200;
// Increase the timeout to give time to attach a debugger
bool debug = package.GetSetting(EnginePackageSettings.DebugAgent, false) ||
package.GetSetting(EnginePackageSettings.PauseBeforeRun, false);
int waitTime = debug ? DEBUG_TIMEOUT : NORMAL_TIMEOUT;
// Wait for agent registration based on the agent actually getting processor time to avoid falling over
// under process starvation.
while (waitTime > agentProcess.TotalProcessorTime.TotalMilliseconds && !agentProcess.HasExited)
{
Thread.Sleep(pollTime);
if (_agentStore.IsReady(agentId, out var agent))
{
log.Debug($"Returning new agent {agentId:B}");
return new TestAgentRemotingProxy(agent, agentId);
}
}
return null;
}
internal bool IsAgentProcessActive(Guid agentId, out Process process)
{
return _agentStore.IsAgentProcessActive(agentId, out process);
}
private void OnAgentExit(Process process, Guid agentId)
{
_agentStore.MarkTerminated(agentId);
string errorMsg;
switch (process.ExitCode)
{
case AgentExitCodes.OK:
return;
case AgentExitCodes.PARENT_PROCESS_TERMINATED:
errorMsg = "Remote test agent believes agency process has exited.";
break;
case AgentExitCodes.UNEXPECTED_EXCEPTION:
errorMsg = "Unhandled exception on remote test agent. " +
"To debug, try running with the --inprocess flag, or using --trace=debug to output logs.";
break;
case AgentExitCodes.FAILED_TO_START_REMOTE_AGENT:
errorMsg = "Failed to start remote test agent.";
break;
case AgentExitCodes.DEBUGGER_SECURITY_VIOLATION:
errorMsg = "Debugger could not be started on remote agent due to System.Security.Permissions.UIPermission not being set.";
break;
case AgentExitCodes.DEBUGGER_NOT_IMPLEMENTED:
errorMsg = "Debugger could not be started on remote agent as not available on platform.";
break;
case AgentExitCodes.UNABLE_TO_LOCATE_AGENCY:
errorMsg = "Remote test agent unable to locate agency process.";
break;
case AgentExitCodes.STACK_OVERFLOW_EXCEPTION:
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
errorMsg = "Remote test agent was terminated due to a stack overflow.";
}
else
{
errorMsg = $"Remote test agent exited with non-zero exit code {process.ExitCode}";
}
break;
default:
errorMsg = $"Remote test agent exited with non-zero exit code {process.ExitCode}";
break;
}
throw new NUnitEngineException(errorMsg);
}
public IServiceLocator ServiceContext { get; set; }
public ServiceStatus Status { get; private set; }
// TODO: it would be better if we had a list of transports to start and stop!
public void StopService()
{
try
{
_remotingTransport.Stop();
_tcpTransport.Stop();
}
finally
{
Status = ServiceStatus.Stopped;
}
}
public void StartService()
{
_runtimeService = ServiceContext.GetService<IRuntimeFrameworkService>();
_availableRuntimeService = ServiceContext.GetService<IAvailableRuntimes>();
if (_runtimeService == null || _availableRuntimeService == null)
{
Status = ServiceStatus.Error;
return;
}
try
{
_remotingTransport.Start();
_tcpTransport.Start();
Status = ServiceStatus.Started;
}
catch
{
Status = ServiceStatus.Error;
throw;
}
}
// TODO: Need to figure out how to incorporate this in the
// new structure, if possible. Originally, Release was only
// called when the nested AgentLease class was disposed.
//public void Release(Guid agentId, ITestAgent agent)
//{
// if (_agentStore.IsAgentProcessActive(agentId, out var process))
// {
// try
// {
// log.Debug("Stopping remote agent");
// agent.Stop();
// }
// catch (SocketException ex)
// {
// int? exitCode;
// try
// {
// exitCode = process.ExitCode;
// }
// catch (NotSupportedException)
// {
// exitCode = null;
// }
// if (exitCode == 0)
// {
// log.Warning("Agent connection was forcibly closed. Exit code was 0, so agent shutdown OK");
// }
// else
// {
// var stopError = $"Agent connection was forcibly closed. Exit code was {exitCode?.ToString() ?? "unknown"}. {Environment.NewLine}{ExceptionHelper.BuildMessageAndStackTrace(ex)}";
// log.Error(stopError);
// throw new NUnitEngineUnloadException(stopError, ex);
// }
// }
// catch (Exception ex)
// {
// var stopError = "Failed to stop the remote agent." + Environment.NewLine + ExceptionHelper.BuildMessageAndStackTrace(ex);
// log.Error(stopError);
// throw new NUnitEngineUnloadException(stopError, ex);
// }
// }
//}
}
}
#endif
| |
//------------------------------------------------------------------------------
// <copyright file="SQLUtility.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">junfang</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
//**************************************************************************
// @File: SQLUtility.cs
//
// Create by: JunFang
//
// Purpose: Implementation of utilities in COM+ SQL Types Library.
// Includes interface INullable, exceptions SqlNullValueException
// and SqlTruncateException, and SQLDebug class.
//
// Notes:
//
// History:
//
// 09/17/99 JunFang Created and implemented as first drop.
//
// @EndHeader@
//**************************************************************************
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
namespace System.Data.SqlTypes {
internal enum EComparison {
LT,
LE,
EQ,
GE,
GT,
NE
}
// This enumeration is used to inquire about internal storage of a SqlBytes or SqlChars instance:
public enum StorageState {
Buffer = 0,
Stream = 1,
UnmanagedBuffer = 2
}
[Serializable]
public class SqlTypeException : SystemException {
public SqlTypeException() : this(Res.GetString(Res.SqlMisc_SqlTypeMessage), null) { // MDAC 82931, 84941
}
// Creates a new SqlTypeException with its message string set to message.
public SqlTypeException(String message) : this(message, null) {
}
public SqlTypeException(String message, Exception e) : base(message, e) { // MDAC 82931
HResult = HResults.SqlType; // MDAC 84941
}
// runtime will call even if private...
// <fxcop ignore=SerializableTypesMustHaveMagicConstructorWithAdequateSecurity />
protected SqlTypeException(SerializationInfo si, StreamingContext sc) : base(SqlTypeExceptionSerialization(si, sc), sc) {
}
static private SerializationInfo SqlTypeExceptionSerialization(SerializationInfo si, StreamingContext sc) {
if ((null != si) && (1 == si.MemberCount)) {
string message = si.GetString("SqlTypeExceptionMessage"); // WebData 104331
SqlTypeException fakeValue = new SqlTypeException(message);
fakeValue.GetObjectData(si, sc);
}
return si;
}
} // SqlTypeException
[Serializable]
public sealed class SqlNullValueException : SqlTypeException {
// Creates a new SqlNullValueException with its message string set to the common string.
public SqlNullValueException() : this(SQLResource.NullValueMessage, null) {
}
// Creates a new NullValueException with its message string set to message.
public SqlNullValueException(String message) : this(message, null) {
}
public SqlNullValueException(String message, Exception e) : base(message, e) { // MDAC 82931
HResult = HResults.SqlNullValue; // MDAC 84941
}
// runtime will call even if private...
// <fxcop ignore=SerializableTypesMustHaveMagicConstructorWithAdequateSecurity />
private SqlNullValueException(SerializationInfo si, StreamingContext sc) : base(SqlNullValueExceptionSerialization(si, sc), sc) {
}
static private SerializationInfo SqlNullValueExceptionSerialization(SerializationInfo si, StreamingContext sc) {
if ((null != si) && (1 == si.MemberCount)) {
string message = si.GetString("SqlNullValueExceptionMessage"); // WebData 104331
SqlNullValueException fakeValue = new SqlNullValueException(message);
fakeValue.GetObjectData(si, sc);
}
return si;
}
} // NullValueException
[Serializable]
public sealed class SqlTruncateException : SqlTypeException {
// Creates a new SqlTruncateException with its message string set to the empty string.
public SqlTruncateException() : this(SQLResource.TruncationMessage, null) {
}
// Creates a new SqlTruncateException with its message string set to message.
public SqlTruncateException(String message) : this(message, null) {
}
public SqlTruncateException(String message, Exception e) : base(message, e) { // MDAC 82931
HResult = HResults.SqlTruncate; // MDAC 84941
}
// runtime will call even if private...
// <fxcop ignore=SerializableTypesMustHaveMagicConstructorWithAdequateSecurity />
private SqlTruncateException(SerializationInfo si, StreamingContext sc) : base(SqlTruncateExceptionSerialization(si, sc), sc) {
}
static private SerializationInfo SqlTruncateExceptionSerialization(SerializationInfo si, StreamingContext sc) {
if ((null != si) && (1 == si.MemberCount)) {
string message = si.GetString("SqlTruncateExceptionMessage"); // WebData 104331
SqlTruncateException fakeValue = new SqlTruncateException(message);
fakeValue.GetObjectData(si, sc);
}
return si;
}
} // SqlTruncateException
[Serializable]
public sealed class SqlNotFilledException : SqlTypeException {
//
// Creates a new SqlNotFilledException with its message string set to the common string.
public SqlNotFilledException() : this(SQLResource.NotFilledMessage, null) {
}
// Creates a new NullValueException with its message string set to message.
public SqlNotFilledException(String message) : this(message, null) {
}
public SqlNotFilledException(String message, Exception e) : base(message, e) { // MDAC 82931
HResult = HResults.SqlNullValue; // MDAC 84941
}
// runtime will call even if private...
// <fxcop ignore=SerializableTypesMustHaveMagicConstructorWithAdequateSecurity />
private SqlNotFilledException(SerializationInfo si, StreamingContext sc) : base(si, sc) {
}
} // SqlNotFilledException
[Serializable]
public sealed class SqlAlreadyFilledException : SqlTypeException {
//
// Creates a new SqlNotFilledException with its message string set to the common string.
public SqlAlreadyFilledException() : this(SQLResource.AlreadyFilledMessage, null) {
}
// Creates a new NullValueException with its message string set to message.
public SqlAlreadyFilledException(String message) : this(message, null) {
}
public SqlAlreadyFilledException(String message, Exception e) : base(message, e) { // MDAC 82931
HResult = HResults.SqlNullValue; // MDAC 84941
}
// runtime will call even if private...
// <fxcop ignore=SerializableTypesMustHaveMagicConstructorWithAdequateSecurity />
private SqlAlreadyFilledException(SerializationInfo si, StreamingContext sc) : base(si, sc) {
}
} // SqlNotFilledException
internal sealed class SQLDebug {
private SQLDebug() { /* prevent utility class from being insantiated*/ }
[System.Diagnostics.Conditional("DEBUG")]
internal static void Check(bool condition) {
Debug.Assert(condition, "", "");
}
[System.Diagnostics.Conditional("DEBUG")]
internal static void Check(bool condition, String conditionString, string message) {
Debug.Assert(condition, conditionString, message);
}
[System.Diagnostics.Conditional("DEBUG")]
internal static void Check(bool condition, String conditionString) {
Debug.Assert(condition, conditionString, "");
}
/*
[System.Diagnostics.Conditional("DEBUG")]
internal static void Message(String traceMessage) {
Debug.WriteLine(SQLResource.MessageString + ": " + traceMessage);
}
*/
} // SQLDebug
} // namespace System.Data.SqlTypes
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// VM appliance
/// First published in XenServer 6.0.
/// </summary>
public partial class VM_appliance : XenObject<VM_appliance>
{
#region Constructors
public VM_appliance()
{
}
public VM_appliance(string uuid,
string name_label,
string name_description,
List<vm_appliance_operation> allowed_operations,
Dictionary<string, vm_appliance_operation> current_operations,
List<XenRef<VM>> VMs)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.VMs = VMs;
}
/// <summary>
/// Creates a new VM_appliance from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VM_appliance(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new VM_appliance from a Proxy_VM_appliance.
/// </summary>
/// <param name="proxy"></param>
public VM_appliance(Proxy_VM_appliance proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VM_appliance.
/// </summary>
public override void UpdateFrom(VM_appliance update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
VMs = update.VMs;
}
internal void UpdateFrom(Proxy_VM_appliance proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<vm_appliance_operation>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_vm_appliance_operation(proxy.current_operations);
VMs = proxy.VMs == null ? null : XenRef<VM>.Create(proxy.VMs);
}
public Proxy_VM_appliance ToProxy()
{
Proxy_VM_appliance result_ = new Proxy_VM_appliance();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.allowed_operations = allowed_operations == null ? new string[] {} : Helper.ObjectListToStringArray(allowed_operations);
result_.current_operations = Maps.convert_to_proxy_string_vm_appliance_operation(current_operations);
result_.VMs = VMs == null ? new string[] {} : Helper.RefListToStringArray(VMs);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VM_appliance
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("allowed_operations"))
allowed_operations = Helper.StringArrayToEnumList<vm_appliance_operation>(Marshalling.ParseStringArray(table, "allowed_operations"));
if (table.ContainsKey("current_operations"))
current_operations = Maps.convert_from_proxy_string_vm_appliance_operation(Marshalling.ParseHashTable(table, "current_operations"));
if (table.ContainsKey("VMs"))
VMs = Marshalling.ParseSetRef<VM>(table, "VMs");
}
public bool DeepEquals(VM_appliance other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._VMs, other._VMs);
}
internal static List<VM_appliance> ProxyArrayToObjectList(Proxy_VM_appliance[] input)
{
var result = new List<VM_appliance>();
foreach (var item in input)
result.Add(new VM_appliance(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, VM_appliance server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
VM_appliance.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
VM_appliance.set_name_description(session, opaqueRef, _name_description);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static VM_appliance get_record(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_record(session.opaque_ref, _vm_appliance);
else
return new VM_appliance(session.proxy.vm_appliance_get_record(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Get a reference to the VM_appliance instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VM_appliance> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VM_appliance>.Create(session.proxy.vm_appliance_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new VM_appliance instance, and return its handle.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VM_appliance> create(Session session, VM_appliance _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_create(session.opaque_ref, _record);
else
return XenRef<VM_appliance>.Create(session.proxy.vm_appliance_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VM_appliance instance, and return its handle.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VM_appliance _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VM_appliance instance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void destroy(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_destroy(session.opaque_ref, _vm_appliance);
else
session.proxy.vm_appliance_destroy(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Destroy the specified VM_appliance instance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_destroy(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_destroy(session.opaque_ref, _vm_appliance);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_destroy(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Get all the VM_appliance instances with the given label.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<VM_appliance>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<VM_appliance>.Create(session.proxy.vm_appliance_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_uuid(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_uuid(session.opaque_ref, _vm_appliance);
else
return session.proxy.vm_appliance_get_uuid(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_name_label(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_name_label(session.opaque_ref, _vm_appliance);
else
return session.proxy.vm_appliance_get_name_label(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_name_description(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_name_description(session.opaque_ref, _vm_appliance);
else
return session.proxy.vm_appliance_get_name_description(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static List<vm_appliance_operation> get_allowed_operations(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_allowed_operations(session.opaque_ref, _vm_appliance);
else
return Helper.StringArrayToEnumList<vm_appliance_operation>(session.proxy.vm_appliance_get_allowed_operations(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Get the current_operations field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static Dictionary<string, vm_appliance_operation> get_current_operations(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_current_operations(session.opaque_ref, _vm_appliance);
else
return Maps.convert_from_proxy_string_vm_appliance_operation(session.proxy.vm_appliance_get_current_operations(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Get the VMs field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static List<XenRef<VM>> get_VMs(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_vms(session.opaque_ref, _vm_appliance);
else
return XenRef<VM>.Create(session.proxy.vm_appliance_get_vms(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Set the name/label field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _vm_appliance, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_set_name_label(session.opaque_ref, _vm_appliance, _label);
else
session.proxy.vm_appliance_set_name_label(session.opaque_ref, _vm_appliance ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _vm_appliance, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_set_name_description(session.opaque_ref, _vm_appliance, _description);
else
session.proxy.vm_appliance_set_name_description(session.opaque_ref, _vm_appliance ?? "", _description ?? "").parse();
}
/// <summary>
/// Start all VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_paused">Instantiate all VMs belonging to this appliance in paused state if set to true.</param>
public static void start(Session session, string _vm_appliance, bool _paused)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_start(session.opaque_ref, _vm_appliance, _paused);
else
session.proxy.vm_appliance_start(session.opaque_ref, _vm_appliance ?? "", _paused).parse();
}
/// <summary>
/// Start all VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_paused">Instantiate all VMs belonging to this appliance in paused state if set to true.</param>
public static XenRef<Task> async_start(Session session, string _vm_appliance, bool _paused)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_start(session.opaque_ref, _vm_appliance, _paused);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_start(session.opaque_ref, _vm_appliance ?? "", _paused).parse());
}
/// <summary>
/// Perform a clean shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void clean_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_clean_shutdown(session.opaque_ref, _vm_appliance);
else
session.proxy.vm_appliance_clean_shutdown(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Perform a clean shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_clean_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_clean_shutdown(session.opaque_ref, _vm_appliance);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_clean_shutdown(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Perform a hard shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void hard_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_hard_shutdown(session.opaque_ref, _vm_appliance);
else
session.proxy.vm_appliance_hard_shutdown(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Perform a hard shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_hard_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_hard_shutdown(session.opaque_ref, _vm_appliance);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_hard_shutdown(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// For each VM in the appliance, try to shut it down cleanly. If this fails, perform a hard shutdown of the VM.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_shutdown(session.opaque_ref, _vm_appliance);
else
session.proxy.vm_appliance_shutdown(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// For each VM in the appliance, try to shut it down cleanly. If this fails, perform a hard shutdown of the VM.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_shutdown(session.opaque_ref, _vm_appliance);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_shutdown(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Assert whether all SRs required to recover this VM appliance are available.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
public static void assert_can_be_recovered(Session session, string _vm_appliance, string _session_to)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_assert_can_be_recovered(session.opaque_ref, _vm_appliance, _session_to);
else
session.proxy.vm_appliance_assert_can_be_recovered(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "").parse();
}
/// <summary>
/// Assert whether all SRs required to recover this VM appliance are available.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
public static XenRef<Task> async_assert_can_be_recovered(Session session, string _vm_appliance, string _session_to)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_assert_can_be_recovered(session.opaque_ref, _vm_appliance, _session_to);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_assert_can_be_recovered(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "").parse());
}
/// <summary>
/// Get the list of SRs required by the VM appliance to recover.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the list of SRs have to be recovered .</param>
public static List<XenRef<SR>> get_SRs_required_for_recovery(Session session, string _vm_appliance, string _session_to)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_srs_required_for_recovery(session.opaque_ref, _vm_appliance, _session_to);
else
return XenRef<SR>.Create(session.proxy.vm_appliance_get_srs_required_for_recovery(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "").parse());
}
/// <summary>
/// Get the list of SRs required by the VM appliance to recover.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the list of SRs have to be recovered .</param>
public static XenRef<Task> async_get_SRs_required_for_recovery(Session session, string _vm_appliance, string _session_to)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_get_srs_required_for_recovery(session.opaque_ref, _vm_appliance, _session_to);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_get_srs_required_for_recovery(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "").parse());
}
/// <summary>
/// Recover the VM appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
/// <param name="_force">Whether the VMs should replace newer versions of themselves.</param>
public static void recover(Session session, string _vm_appliance, string _session_to, bool _force)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_recover(session.opaque_ref, _vm_appliance, _session_to, _force);
else
session.proxy.vm_appliance_recover(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "", _force).parse();
}
/// <summary>
/// Recover the VM appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
/// <param name="_force">Whether the VMs should replace newer versions of themselves.</param>
public static XenRef<Task> async_recover(Session session, string _vm_appliance, string _session_to, bool _force)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_recover(session.opaque_ref, _vm_appliance, _session_to, _force);
else
return XenRef<Task>.Create(session.proxy.async_vm_appliance_recover(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "", _force).parse());
}
/// <summary>
/// Return a list of all the VM_appliances known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VM_appliance>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_all(session.opaque_ref);
else
return XenRef<VM_appliance>.Create(session.proxy.vm_appliance_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the VM_appliance Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VM_appliance>, VM_appliance> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_all_records(session.opaque_ref);
else
return XenRef<VM_appliance>.Create<Proxy_VM_appliance>(session.proxy.vm_appliance_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<vm_appliance_operation> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
Changed = true;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<vm_appliance_operation> _allowed_operations = new List<vm_appliance_operation>() {};
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, vm_appliance_operation> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
Changed = true;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, vm_appliance_operation> _current_operations = new Dictionary<string, vm_appliance_operation>() {};
/// <summary>
/// all VMs in this appliance
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VM>))]
public virtual List<XenRef<VM>> VMs
{
get { return _VMs; }
set
{
if (!Helper.AreEqual(value, _VMs))
{
_VMs = value;
Changed = true;
NotifyPropertyChanged("VMs");
}
}
}
private List<XenRef<VM>> _VMs = new List<XenRef<VM>>() {};
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Util
{
using System;
using NPOI.SS.UserModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
/**
* Helper methods for when working with Usermodel sheets
*
* @author Yegor Kozlov
*/
public class SheetUtil
{
// /**
// * Excel measures columns in units of 1/256th of a character width
// * but the docs say nothing about what particular character is used.
// * '0' looks to be a good choice.
// */
private static char defaultChar = '0';
// /**
// * This is the multiple that the font height is scaled by when determining the
// * boundary of rotated text.
// */
//private static double fontHeightMultiple = 2.0;
/**
* Dummy formula Evaluator that does nothing.
* YK: The only reason of having this class is that
* {@link NPOI.SS.UserModel.DataFormatter#formatCellValue(NPOI.SS.UserModel.Cell)}
* returns formula string for formula cells. Dummy Evaluator Makes it to format the cached formula result.
*
* See Bugzilla #50021
*/
private static IFormulaEvaluator dummyEvaluator = new DummyEvaluator();
public class DummyEvaluator : IFormulaEvaluator
{
public void ClearAllCachedResultValues() { }
public void NotifySetFormula(ICell cell) { }
public void NotifyDeleteCell(ICell cell) { }
public void NotifyUpdateCell(ICell cell) { }
public CellValue Evaluate(ICell cell) { return null; }
public ICell EvaluateInCell(ICell cell) { return null; }
public void EvaluateAll() { }
public CellType EvaluateFormulaCell(ICell cell)
{
return cell.CachedFormulaResultType;
}
public bool DebugEvaluationOutputForNextEval
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
public static IRow CopyRow(ISheet sourceSheet, int sourceRowIndex, ISheet targetSheet, int targetRowIndex)
{
// Get the source / new row
IRow newRow = targetSheet.GetRow(targetRowIndex);
IRow sourceRow = sourceSheet.GetRow(sourceRowIndex);
// If the row exist in destination, push down all rows by 1 else create a new row
if (newRow != null)
{
targetSheet.RemoveRow(newRow);
}
newRow = targetSheet.CreateRow(targetRowIndex);
if (sourceRow == null)
throw new ArgumentNullException("source row doesn't exist");
// Loop through source columns to add to new row
for (int i = sourceRow.FirstCellNum; i < sourceRow.LastCellNum; i++)
{
// Grab a copy of the old/new cell
ICell oldCell = sourceRow.GetCell(i);
// If the old cell is null jump to next cell
if (oldCell == null)
{
continue;
}
ICell newCell = newRow.CreateCell(i);
if (oldCell.CellStyle != null)
{
// apply style from old cell to new cell
newCell.CellStyle = oldCell.CellStyle;
}
// If there is a cell comment, copy
if (oldCell.CellComment != null)
{
newCell.CellComment = oldCell.CellComment;
}
// If there is a cell hyperlink, copy
if (oldCell.Hyperlink != null)
{
newCell.Hyperlink = oldCell.Hyperlink;
}
// Set the cell data type
newCell.SetCellType(oldCell.CellType);
// Set the cell data value
switch (oldCell.CellType)
{
case CellType.Blank:
newCell.SetCellValue(oldCell.StringCellValue);
break;
case CellType.Boolean:
newCell.SetCellValue(oldCell.BooleanCellValue);
break;
case CellType.Error:
newCell.SetCellErrorValue(oldCell.ErrorCellValue);
break;
case CellType.Formula:
newCell.SetCellFormula(oldCell.CellFormula);
break;
case CellType.Numeric:
newCell.SetCellValue(oldCell.NumericCellValue);
break;
case CellType.String:
newCell.SetCellValue(oldCell.RichStringCellValue);
break;
}
}
// If there are are any merged regions in the source row, copy to new row
for (int i = 0; i < sourceSheet.NumMergedRegions; i++)
{
CellRangeAddress cellRangeAddress = sourceSheet.GetMergedRegion(i);
if (cellRangeAddress.FirstRow == sourceRow.RowNum)
{
CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.RowNum,
(newRow.RowNum +
(cellRangeAddress.LastRow - cellRangeAddress.FirstRow
)),
cellRangeAddress.FirstColumn,
cellRangeAddress.LastColumn);
targetSheet.AddMergedRegion(newCellRangeAddress);
}
}
return newRow;
}
public static IRow CopyRow(ISheet sheet, int sourceRowIndex, int targetRowIndex)
{
if (sourceRowIndex == targetRowIndex)
throw new ArgumentException("sourceIndex and targetIndex cannot be same");
// Get the source / new row
IRow newRow = sheet.GetRow(targetRowIndex);
IRow sourceRow = sheet.GetRow(sourceRowIndex);
// If the row exist in destination, push down all rows by 1 else create a new row
if (newRow != null)
{
sheet.ShiftRows(targetRowIndex, sheet.LastRowNum, 1);
}
else
{
newRow = sheet.CreateRow(targetRowIndex);
}
// Loop through source columns to add to new row
for (int i = sourceRow.FirstCellNum; i < sourceRow.LastCellNum; i++)
{
// Grab a copy of the old/new cell
ICell oldCell = sourceRow.GetCell(i);
// If the old cell is null jump to next cell
if (oldCell == null)
{
continue;
}
ICell newCell = newRow.CreateCell(i);
if (oldCell.CellStyle != null)
{
// apply style from old cell to new cell
newCell.CellStyle = oldCell.CellStyle;
}
// If there is a cell comment, copy
if (oldCell.CellComment != null)
{
newCell.CellComment = oldCell.CellComment;
}
// If there is a cell hyperlink, copy
if (oldCell.Hyperlink != null)
{
newCell.Hyperlink = oldCell.Hyperlink;
}
// Set the cell data type
newCell.SetCellType(oldCell.CellType);
// Set the cell data value
switch (oldCell.CellType)
{
case CellType.Blank:
newCell.SetCellValue(oldCell.StringCellValue);
break;
case CellType.Boolean:
newCell.SetCellValue(oldCell.BooleanCellValue);
break;
case CellType.Error:
newCell.SetCellErrorValue(oldCell.ErrorCellValue);
break;
case CellType.Formula:
newCell.SetCellFormula(oldCell.CellFormula);
break;
case CellType.Numeric:
newCell.SetCellValue(oldCell.NumericCellValue);
break;
case CellType.String:
newCell.SetCellValue(oldCell.RichStringCellValue);
break;
}
}
// If there are are any merged regions in the source row, copy to new row
for (int i = 0; i < sheet.NumMergedRegions; i++)
{
CellRangeAddress cellRangeAddress = sheet.GetMergedRegion(i);
if (cellRangeAddress.FirstRow == sourceRow.RowNum)
{
CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.RowNum,
(newRow.RowNum +
(cellRangeAddress.LastRow - cellRangeAddress.FirstRow
)),
cellRangeAddress.FirstColumn,
cellRangeAddress.LastColumn);
sheet.AddMergedRegion(newCellRangeAddress);
}
}
return newRow;
}
/**
* Compute width of a single cell
*
* @param cell the cell whose width is to be calculated
* @param defaultCharWidth the width of a single character
* @param formatter formatter used to prepare the text to be measured
* @param useMergedCells whether to use merged cells
* @return the width in pixels
*/
public static double GetCellWidth(ICell cell, int defaultCharWidth, DataFormatter formatter, bool useMergedCells)
{
ISheet sheet = cell.Sheet;
IWorkbook wb = sheet.Workbook;
IRow row = cell.Row;
int column = cell.ColumnIndex;
int colspan = 1;
for (int i = 0; i < sheet.NumMergedRegions; i++)
{
CellRangeAddress region = sheet.GetMergedRegion(i);
if (ContainsCell(region, row.RowNum, column))
{
if (!useMergedCells)
{
// If we're not using merged cells, skip this one and move on to the next.
return -1;
}
cell = row.GetCell(region.FirstColumn);
colspan = 1 + region.LastColumn - region.FirstColumn;
}
}
ICellStyle style = cell.CellStyle;
CellType cellType = cell.CellType;
IFont defaultFont = wb.GetFontAt((short)0);
Font windowsFont = IFont2Font(defaultFont);
// for formula cells we compute the cell width for the cached formula result
if (cellType == CellType.Formula) cellType = cell.CachedFormulaResultType;
IFont font = wb.GetFontAt(style.FontIndex);
//AttributedString str;
//TextLayout layout;
double width = -1;
using (Bitmap bmp = new Bitmap(2048, 100))
using (Graphics g = Graphics.FromImage(bmp))
{
if (cellType == CellType.String)
{
IRichTextString rt = cell.RichStringCellValue;
String[] lines = rt.String.Split("\n".ToCharArray());
for (int i = 0; i < lines.Length; i++)
{
String txt = lines[i] + defaultChar;
//str = new AttributedString(txt);
//copyAttributes(font, str, 0, txt.length());
windowsFont = IFont2Font(font);
if (rt.NumFormattingRuns > 0)
{
// TODO: support rich text fragments
}
//layout = new TextLayout(str.getIterator(), fontRenderContext);
if (style.Rotation != 0)
{
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
//AffineTransform trans = new AffineTransform();
//trans.concatenate(AffineTransform.getRotateInstance(style.Rotation*2.0*Math.PI/360.0));
//trans.concatenate(
// AffineTransform.getScaleInstance(1, fontHeightMultiple)
// );
double angle = style.Rotation * 2.0 * Math.PI / 360.0;
SizeF sf = g.MeasureString(txt, windowsFont);
double x1 = Math.Abs(sf.Height * Math.Sin(angle));
double x2 = Math.Abs(sf.Width * Math.Cos(angle));
double w = Math.Round(x1 + x2, 0, MidpointRounding.ToEven);
width = Math.Max(width, (w / colspan / defaultCharWidth) * 2 + cell.CellStyle.Indention);
//width = Math.Max(width,
// ((layout.getOutline(trans).getBounds().getWidth()/colspan)/defaultCharWidth) +
// cell.getCellStyle().getIndention());
}
else
{
//width = Math.Max(width,
// ((layout.getBounds().getWidth()/colspan)/defaultCharWidth) +
// cell.getCellStyle().getIndention());
double w = Math.Round(g.MeasureString(txt, windowsFont).Width, 0, MidpointRounding.ToEven);
width = Math.Max(width, (w / colspan / defaultCharWidth) * 2 + cell.CellStyle.Indention);
}
}
}
else
{
String sval = null;
if (cellType == CellType.Numeric)
{
// Try to get it formatted to look the same as excel
try
{
sval = formatter.FormatCellValue(cell, dummyEvaluator);
}
catch (Exception)
{
sval = cell.NumericCellValue.ToString();
}
}
else if (cellType == CellType.Boolean)
{
sval = cell.BooleanCellValue.ToString().ToUpper();
}
if (sval != null)
{
String txt = sval + defaultChar;
//str = new AttributedString(txt);
//copyAttributes(font, str, 0, txt.length());
windowsFont = IFont2Font(font);
//layout = new TextLayout(str.getIterator(), fontRenderContext);
if (style.Rotation != 0)
{
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
//AffineTransform trans = new AffineTransform();
//trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
//trans.concatenate(
// AffineTransform.getScaleInstance(1, fontHeightMultiple)
// );
//width = Math.max(width,
// ((layout.getOutline(trans).getBounds().getWidth()/colspan)/defaultCharWidth) +
// cell.getCellStyle().getIndention());
double angle = style.Rotation * 2.0 * Math.PI / 360.0;
SizeF sf = g.MeasureString(txt, windowsFont);
double x1 = sf.Height * Math.Sin(angle);
double x2 = sf.Width * Math.Cos(angle);
double w = Math.Round(x1 + x2, 0, MidpointRounding.ToEven);
width = Math.Max(width, (w / colspan / defaultCharWidth) * 2 + cell.CellStyle.Indention);
}
else
{
//width = Math.max(width,
// ((layout.getBounds().getWidth()/colspan)/defaultCharWidth) +
// cell.getCellStyle().getIndention());
double w = Math.Round(g.MeasureString(txt, windowsFont).Width, 0, MidpointRounding.ToEven);
width = Math.Max(width, (w * 1.0 / colspan / defaultCharWidth) * 2 + cell.CellStyle.Indention);
}
}
}
}
return width;
}
// /**
// * Drawing context to measure text
// */
//private static FontRenderContext fontRenderContext = new FontRenderContext(null, true, true);
/**
* Compute width of a column and return the result
*
* @param sheet the sheet to calculate
* @param column 0-based index of the column
* @param useMergedCells whether to use merged cells
* @return the width in pixels
*/
public static double GetColumnWidth(ISheet sheet, int column, bool useMergedCells)
{
//AttributedString str;
//TextLayout layout;
IWorkbook wb = sheet.Workbook;
DataFormatter formatter = new DataFormatter();
IFont defaultFont = wb.GetFontAt((short) 0);
//str = new AttributedString((defaultChar));
//copyAttributes(defaultFont, str, 0, 1);
//layout = new TextLayout(str.Iterator, fontRenderContext);
//int defaultCharWidth = (int)layout.Advance;
Font font = IFont2Font(defaultFont);
int defaultCharWidth = TextRenderer.MeasureText("" + new String(defaultChar, 1), font).Width;
//DummyEvaluator dummyEvaluator = new DummyEvaluator();
double width = -1;
foreach (IRow row in sheet)
{
ICell cell = row.GetCell(column);
if (cell == null)
{
continue;
}
double cellWidth = GetCellWidth(cell, defaultCharWidth, formatter, useMergedCells);
width = Math.Max(width, cellWidth);
}
return width;
}
/**
* Compute width of a column based on a subset of the rows and return the result
*
* @param sheet the sheet to calculate
* @param column 0-based index of the column
* @param useMergedCells whether to use merged cells
* @param firstRow 0-based index of the first row to consider (inclusive)
* @param lastRow 0-based index of the last row to consider (inclusive)
* @return the width in pixels
*/
public static double GetColumnWidth(ISheet sheet, int column, bool useMergedCells, int firstRow, int lastRow)
{
IWorkbook wb = sheet.Workbook;
DataFormatter formatter = new DataFormatter();
IFont defaultFont = wb.GetFontAt((short)0);
//str = new AttributedString((defaultChar));
//copyAttributes(defaultFont, str, 0, 1);
//layout = new TextLayout(str.Iterator, fontRenderContext);
//int defaultCharWidth = (int)layout.Advance;
Font font = IFont2Font(defaultFont);
int defaultCharWidth = TextRenderer.MeasureText("" + new String(defaultChar, 1), font).Width;
double width = -1;
for (int rowIdx = firstRow; rowIdx <= lastRow; ++rowIdx)
{
IRow row = sheet.GetRow(rowIdx);
if (row != null)
{
ICell cell = row.GetCell(column);
if (cell == null)
{
continue;
}
double cellWidth = GetCellWidth(cell, defaultCharWidth, formatter, useMergedCells);
width = Math.Max(width, cellWidth);
}
}
return width;
}
// /**
// * Copy text attributes from the supplied Font to Java2D AttributedString
// */
//private static void copyAttributes(IFont font, AttributedString str, int startIdx, int endIdx)
//{
// str.AddAttribute(TextAttribute.FAMILY, font.FontName, startIdx, endIdx);
// str.AddAttribute(TextAttribute.SIZE, (float)font.FontHeightInPoints);
// if (font.Boldweight == (short)FontBoldWeight.BOLD) str.AddAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIdx, endIdx);
// if (font.IsItalic) str.AddAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIdx, endIdx);
// if (font.Underline == (byte)FontUnderlineType.SINGLE) str.AddAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIdx, endIdx);
//}
/// <summary>
/// Convert HSSFFont to Font.
/// </summary>
/// <param name="font1">The font.</param>
/// <returns></returns>
internal static Font IFont2Font(IFont font1)
{
FontStyle style = FontStyle.Regular;
if (font1.Boldweight == (short)FontBoldWeight.Bold)
{
style |= FontStyle.Bold;
}
if (font1.IsItalic)
style |= FontStyle.Italic;
if (font1.Underline == FontUnderlineType.Single)
{
style |= FontStyle.Underline;
}
Font font = new Font(font1.FontName, font1.FontHeightInPoints, style, GraphicsUnit.Point);
return font;
//return new System.Drawing.Font(font1.FontName, font1.FontHeightInPoints);
}
public static bool ContainsCell(CellRangeAddress cr, int rowIx, int colIx)
{
if (cr.FirstRow <= rowIx && cr.LastRow >= rowIx
&& cr.FirstColumn <= colIx && cr.LastColumn >= colIx)
{
return true;
}
return false;
}
/**
* Generate a valid sheet name based on the existing one. Used when cloning sheets.
*
* @param srcName the original sheet name to
* @return clone sheet name
*/
public static String GetUniqueSheetName(IWorkbook wb, String srcName)
{
int uniqueIndex = 2;
String baseName = srcName;
int bracketPos = srcName.LastIndexOf('(');
if (bracketPos > 0 && srcName.EndsWith(")"))
{
String suffix = srcName.Substring(bracketPos + 1, srcName.Length - bracketPos - 2);
try
{
uniqueIndex = Int32.Parse(suffix.Trim());
uniqueIndex++;
baseName = srcName.Substring(0, bracketPos).Trim();
}
catch (FormatException)
{
// contents of brackets not numeric
}
}
while (true)
{
// Try and find the next sheet name that is unique
String index = (uniqueIndex++).ToString();
String name;
if (baseName.Length + index.Length + 2 < 31)
{
name = baseName + " (" + index + ")";
}
else
{
name = baseName.Substring(0, 31 - index.Length - 2) + "(" + index + ")";
}
//If the sheet name is unique, then Set it otherwise Move on to the next number.
if (wb.GetSheetIndex(name) == -1)
{
return name;
}
}
}
}
public struct _Size
{
public static readonly _Size Empty = new _Size();
public static readonly _Size DefaultFont = new _Size(12, 12); // default
public int Width { get; set; }
public int Height { get; set; }
public _Size(Point pt) : this(pt.X, pt.Y) { }
public _Size(int x, int y)
{
Width = x;
Height = y;
}
}
internal class TextRenderer
{
/// MeasureText wrappers.
partial class IntNativeMethods
{
[DllImport("User32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
public static extern int DrawTextExW(HandleRef hDC, string lpszString, int nCount,
ref IntNativeMethods.RECT lpRect, int nFormat, [In, Out] IntNativeMethods.DRAWTEXTPARAMS lpDTParams);
/// </devdoc>
[DllImport("Gdi32.dll", SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteDC", CharSet = CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool IntDeleteDC(HandleRef hDC);
public static bool DeleteDC(HandleRef hDC)
{
// System.Internal.HandleCollector.Remove((IntPtr)hDC, IntSafeNativeMethods.CommonHandles.GDI);
bool retVal = IntDeleteDC(hDC);
return retVal;
}
[DllImport("Gdi32.dll", SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleDC", CharSet = CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern IntPtr IntCreateCompatibleDC(HandleRef hDC);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr CreateCompatibleDC(HandleRef hDC)
{
// System.Internal.HandleCollector.Add(
IntPtr compatibleDc = IntCreateCompatibleDC(hDC); // , IntSafeNativeMethods.CommonHandles.GDI);
// DbgUtil.AssertWin32(compatibleDc != IntPtr.Zero, "CreateCompatibleDC([hdc=0x{0:X8}]) failed", hDC.Handle);
return compatibleDc;
}
#region stru
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public RECT(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
}
[StructLayout(LayoutKind.Sequential)]
public class DRAWTEXTPARAMS
{
private int cbSize = Marshal.SizeOf(typeof(DRAWTEXTPARAMS));
public int iTabLength;
public int iLeftMargin;
public int iRightMargin;
/// <devdoc>
/// Receives the number of characters processed by DrawTextEx, including white-space characters.
/// The number can be the length of the string or the index of the first line that falls below the drawing area.
/// Note that DrawTextEx always processes the entire string if the DT_NOCLIP formatting flag is specified.
/// </devdoc>
public int uiLengthDrawn;
public DRAWTEXTPARAMS()
{
}
public DRAWTEXTPARAMS(DRAWTEXTPARAMS original)
{
this.iLeftMargin = original.iLeftMargin;
this.iRightMargin = original.iRightMargin;
this.iTabLength = original.iTabLength;
}
public DRAWTEXTPARAMS(int leftMargin, int rightMargin)
{
this.iLeftMargin = leftMargin;
this.iRightMargin = rightMargin;
}
}
#endregion
}
public static _Size MeasureText(string text, Font font)
{
if (string.IsNullOrEmpty(text))
{
return _Size.Empty;
}
_Size result = _Size.DefaultFont;
using (WindowsGraphics grf = WindowsGraphics.CreateMeasurementWindowsGraphics())
{
// WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font))
result = TextRenderer.MeasureText(grf.DeviceContext, text, font);
// WindowsGraphicsCacheManager.MeasurementGraphics.MeasureText(text, wf);
return result;
}
}
public static _Size MeasureText(_DeviceContext context, string text, Font font)
{
_Size result = _Size.Empty;
return result;
}
//class WindowsGraphicsCacheManager
//{
// // From MSDN: Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once,
// // when the class constructor executes, and therefore affects only one thread.
// // WindowsGraphics object used for measuring text based on the screen DC. TLS to avoid synchronization issues.
// // [ThreadStatic]
// // private static WindowsGraphics measurementGraphics;
//}
internal enum DeviceContextType
{
Display = 0,
Memory = 1,
}
internal class _DeviceContext : IDisposable
{
public IntPtr hDC { get; set; }
internal DeviceContextType Type { get; set; }
public _DeviceContext(IntPtr compatibleDc, DeviceContextType type)
{
// System.Drawing.Internal.DeviceContext
hDC = compatibleDc;
}
public static _DeviceContext FromCompatibleDC(IntPtr hdc) // = IntPtr.Zero)
{
IntPtr compatibleDc = IntNativeMethods.CreateCompatibleDC(new HandleRef(null, hdc));
return new _DeviceContext(compatibleDc, DeviceContextType.Memory);
}
public void Dispose()
{
IntNativeMethods.DeleteDC(new HandleRef(this, this.hDC));
}
}
public class WindowsGraphics : IDisposable
{
public bool disposeDc = false;
public _DeviceContext DeviceContext { get; set; }
public WindowsGraphics(_DeviceContext dc = null)
{
this.DeviceContext = dc ?? _DeviceContext.FromCompatibleDC(IntPtr.Zero);
}
public static WindowsGraphics CreateMeasurementWindowsGraphics()
{
_DeviceContext dc = _DeviceContext.FromCompatibleDC(IntPtr.Zero);
WindowsGraphics wg = new WindowsGraphics(dc);
wg.disposeDc = true; // we create it, we dispose it.
return wg;
}
public void Dispose()
{
if (disposeDc && DeviceContext != null)
DeviceContext.Dispose();
DeviceContext = null;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class RemoveObjTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
HybridDictionary hd;
const int BIG_LENGTH = 100;
// simple string values
string[] valuesShort =
{
"",
" ",
"$%^#",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keysShort =
{
Int32.MaxValue.ToString(),
" ",
System.DateTime.Today.ToString(),
"",
"$%^#"
};
string[] valuesLong = new string[BIG_LENGTH];
string[] keysLong = new string[BIG_LENGTH];
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
for (int i = 0; i < BIG_LENGTH; i++)
{
valuesLong[i] = "Item" + i;
keysLong[i] = "keY" + i;
}
// [] HybridDictionary is constructed as expected
//-----------------------------------------------------------------
hd = new HybridDictionary();
// [] Remove() on empty dictionary
//
cnt = hd.Count;
try
{
hd.Remove(null);
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
cnt = hd.Count;
hd.Remove("some_string");
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)"));
}
cnt = hd.Count;
hd.Remove(new Hashtable());
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)"));
}
//
// [] Remove() on short dictionary with simple strings
//
cnt = hd.Count;
int len = valuesShort.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, valuesShort.Length));
}
//
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(keysShort[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysShort[i]))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
// remove second time
hd.Remove(keysShort[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed when Remove() second time", i));
}
}
// [] Remove() on long dictionary with simple strings
//
hd.Clear();
cnt = hd.Count;
len = valuesLong.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
//
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(keysLong[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i]))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
// remove second time
hd.Remove(keysLong[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed when Remove() second time", i));
}
}
//
// [] Remove() on long dictionary with Intl strings
// Intl strings
//
len = valuesLong.Length;
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
cnt = hd.Count;
for (int i = 0; i < len; i++)
{
hd.Add(intlValues[i + len], intlValues[i]);
}
if (hd.Count != (cnt + len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
}
for (int i = 0; i < len; i++)
{
//
cnt = hd.Count;
hd.Remove(intlValues[i + len]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
// [] Remove() on short dictionary with Intl strings
//
len = valuesShort.Length;
hd.Clear();
cnt = hd.Count;
for (int i = 0; i < len; i++)
{
hd.Add(intlValues[i + len], intlValues[i]);
}
if (hd.Count != (cnt + len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
}
for (int i = 0; i < len; i++)
{
//
cnt = hd.Count;
hd.Remove(intlValues[i + len]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
//
// Case sensitivity
// [] Case sensitivity - hashtable
//
len = valuesLong.Length;
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
cnt = hd.Count;
hd.Remove(keysLong[i].ToUpper());
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i].ToUpper()))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
// LD is case-sensitive by default
for (int i = 0; i < len; i++)
{
// lowercase key
cnt = hd.Count;
hd.Remove(keysLong[i].ToLower());
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i));
}
}
//
// [] Case sensitivity - list
len = valuesShort.Length;
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
cnt = hd.Count;
hd.Remove(keysLong[i].ToUpper());
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i].ToUpper()))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
// LD is case-sensitive by default
for (int i = 0; i < len; i++)
{
// lowercase key
cnt = hd.Count;
hd.Remove(keysLong[i].ToLower());
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i));
}
}
//
// [] Remove() on case-insensitive HD - list
//
hd = new HybridDictionary(true);
len = valuesShort.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower());
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(keysLong[i].ToUpper());
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i].ToLower()))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
//
// [] Remove() on case-insensitive HD - hashtable
//
hd = new HybridDictionary(true);
len = valuesLong.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower());
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(keysLong[i].ToUpper());
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove item", i));
}
if (hd.Contains(keysLong[i].ToLower()))
{
Assert.False(true, string.Format("Error, removed wrong item", i));
}
}
//
// [] Remove(null) from filled HD - list
//
hd = new HybridDictionary();
len = valuesShort.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
try
{
hd.Remove(null);
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
//
// [] Remove(null) from filled HD - hashtable
//
hd = new HybridDictionary();
len = valuesLong.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
try
{
hd.Remove(null);
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
//
// [] Remove(special_object) from filled HD - list
//
hd = new HybridDictionary();
hd.Clear();
len = 2;
ArrayList[] b = new ArrayList[len];
Hashtable[] lbl = new Hashtable[len];
for (int i = 0; i < len; i++)
{
lbl[i] = new Hashtable();
b[i] = new ArrayList();
hd.Add(lbl[i], b[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(lbl[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove special object"));
}
if (hd.Contains(lbl[i]))
{
Assert.False(true, string.Format("Error, removed wrong special object"));
}
}
//
// [] Remove(special_object) from filled HD - hashtable
//
hd = new HybridDictionary();
hd.Clear();
len = 40;
b = new ArrayList[len];
lbl = new Hashtable[len];
for (int i = 0; i < len; i++)
{
lbl[i] = new Hashtable();
b[i] = new ArrayList();
hd.Add(lbl[i], b[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd.Remove(lbl[i]);
if (hd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, failed to remove special object"));
}
if (hd.Contains(lbl[i]))
{
Assert.False(true, string.Format("Error, removed wrong special object"));
}
}
}
}
}
| |
//******************************************************************************************************************************************************************************************//
// Public Domain //
// //
// Written by Peter O. in 2014. //
// //
// Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ //
// //
// If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ //
//******************************************************************************************************************************************************************************************//
using System;
using System.Text;
namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers
{
internal static class EFloatByteArrayString {
internal static EFloat FromString(
byte[] chars,
int offset,
int length,
EContext ctx,
bool throwException) {
if (chars == null) {
if (!throwException) {
return null;
} else {
throw new ArgumentNullException(nameof(chars));
}
}
if (offset < 0) {
if (!throwException) {
return null;
} else { throw new FormatException("offset(" + offset + ") is not" +
"\u0020greater" + "\u0020or equal to 0");
}
}
if (offset > chars.Length) {
if (!throwException) {
return null;
} else { throw new FormatException("offset(" + offset + ") is not" +
"\u0020less" + "\u0020or" + "\u0020equal to " + chars.Length);
}
}
if (length < 0) {
if (!throwException) {
return null;
} else { throw new FormatException("length(" + length + ") is not" +
"\u0020greater or" + "\u0020equal to 0");
}
}
if (length > chars.Length) {
if (!throwException) {
return null;
} else { throw new FormatException("length(" + length + ") is not" +
"\u0020less" + "\u0020or" + "\u0020equal to " + chars.Length);
}
}
if (chars.Length - offset < length) {
if (!throwException) {
return null;
} else {
throw new FormatException("str's length minus " + offset + "(" +
(chars.Length - offset) + ") is not greater or equal to " + length);
}
}
EContext b64 = EContext.Binary64;
if (ctx != null && ctx.HasMaxPrecision && ctx.HasExponentRange &&
!ctx.IsSimplified && ctx.EMax.CompareTo(b64.EMax) <= 0 &&
ctx.EMin.CompareTo(b64.EMin) >= 0 &&
ctx.Precision.CompareTo(b64.Precision) <= 0) {
int tmpoffset = offset;
int endpos = offset + length;
if (length == 0) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
if (chars[tmpoffset] == '-' || chars[tmpoffset] == '+') {
++tmpoffset;
}
if (tmpoffset < endpos && ((chars[tmpoffset] >= '0' &&
chars[tmpoffset] <= '9') || chars[tmpoffset] == '.')) {
EFloat ef = DoubleEFloatFromString(
chars,
offset,
length,
ctx,
throwException);
if (ef != null) {
return ef;
}
}
}
return EDecimal.FromString(
chars,
offset,
length,
EContext.Unlimited.WithSimplified(ctx != null && ctx.IsSimplified))
.ToEFloat(ctx);
}
internal static EFloat DoubleEFloatFromString(
byte[] chars,
int offset,
int length,
EContext ctx,
bool throwException) {
int tmpoffset = offset;
if (chars == null) {
if (!throwException) {
return null;
} else {
throw new ArgumentNullException(nameof(chars));
}
}
if (length == 0) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
int endStr = tmpoffset + length;
var negative = false;
var haveDecimalPoint = false;
var haveDigits = false;
var haveExponent = false;
var newScaleInt = 0;
var digitStart = 0;
int i = tmpoffset;
long mantissaLong = 0L;
// Ordinary number
if (chars[i] == '+' || chars[i] == '-') {
if (chars[i] == '-') {
negative = true;
}
++i;
}
digitStart = i;
int digitEnd = i;
int decimalDigitStart = i;
var haveNonzeroDigit = false;
var decimalPrec = 0;
int decimalDigitEnd = i;
var nonzeroBeyondMax = false;
var lastdigit = -1;
// 768 is maximum precision of a decimal
// half-ULP in double format
var maxDecimalPrec = 768;
if (length > 21) {
int eminInt = ctx.EMin.ToInt32Checked();
int emaxInt = ctx.EMax.ToInt32Checked();
int precInt = ctx.Precision.ToInt32Checked();
if (eminInt >= -14 && emaxInt <= 15) {
maxDecimalPrec = (precInt <= 11) ? 21 : 63;
} else if (eminInt >= -126 && emaxInt <= 127) {
maxDecimalPrec = (precInt <= 24) ? 113 : 142;
}
}
for (; i < endStr; ++i) {
byte ch = chars[i];
if (ch >= '0' && ch <= '9') {
var thisdigit = (int)(ch - '0');
haveDigits = true;
haveNonzeroDigit |= thisdigit != 0;
if (decimalPrec > maxDecimalPrec) {
if (thisdigit != 0) {
nonzeroBeyondMax = true;
}
if (!haveDecimalPoint) {
// NOTE: Absolute value will not be more than
// the byte[] portion's length, so will fit comfortably
// in an 'int'.
newScaleInt = checked(newScaleInt + 1);
}
continue;
}
lastdigit = thisdigit;
if (haveNonzeroDigit) {
++decimalPrec;
}
if (haveDecimalPoint) {
decimalDigitEnd = i + 1;
} else {
digitEnd = i + 1;
}
if (mantissaLong <= 922337203685477580L) {
mantissaLong *= 10;
mantissaLong += thisdigit;
} else {
mantissaLong = Int64.MaxValue;
}
if (haveDecimalPoint) {
// NOTE: Absolute value will not be more than
// the portion's length, so will fit comfortably
// in an 'int'.
newScaleInt = checked(newScaleInt - 1);
}
} else if (ch == '.') {
if (haveDecimalPoint) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
haveDecimalPoint = true;
decimalDigitStart = i + 1;
decimalDigitEnd = i + 1;
} else if (ch == 'E' || ch == 'e') {
haveExponent = true;
++i;
break;
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
if (!haveDigits) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
var expInt = 0;
var expoffset = 1;
var expDigitStart = -1;
var expPrec = 0;
bool zeroMantissa = !haveNonzeroDigit;
haveNonzeroDigit = false;
EFloat ef1, ef2;
if (haveExponent) {
haveDigits = false;
if (i == endStr) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
byte ch = chars[i];
if (ch == '+' || ch == '-') {
if (ch == '-') {
expoffset = -1;
}
++i;
}
expDigitStart = i;
for (; i < endStr; ++i) {
ch = chars[i];
if (ch >= '0' && ch <= '9') {
haveDigits = true;
var thisdigit = (int)(ch - '0');
haveNonzeroDigit |= thisdigit != 0;
if (haveNonzeroDigit) {
++expPrec;
}
if (expInt <= 214748364) {
expInt *= 10;
expInt += thisdigit;
} else {
expInt = Int32.MaxValue;
}
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
if (!haveDigits) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
expInt *= expoffset;
if (expPrec > 12) {
// Exponent that can't be compensated by digit
// length without remaining beyond Int32 range
if (expoffset < 0) {
return EFloat.SignalUnderflow(ctx, negative, zeroMantissa);
} else {
return EFloat.SignalOverflow(ctx, negative, zeroMantissa);
}
}
}
if (i != endStr) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
if (expInt != Int32.MaxValue && expInt > -Int32.MaxValue &&
mantissaLong != Int64.MaxValue && (ctx == null ||
!ctx.HasFlagsOrTraps)) {
if (mantissaLong == 0) {
EFloat ef = EFloat.Create(
EInteger.Zero,
EInteger.FromInt32(expInt));
if (negative) {
ef = ef.Negate();
}
return ef.RoundToPrecision(ctx);
}
var finalexp = (long)expInt + (long)newScaleInt;
long ml = mantissaLong;
if (finalexp >= -22 && finalexp <= 44) {
var iexp = (int)finalexp;
while (ml <= 900719925474099L && iexp > 22) {
ml *= 10;
--iexp;
}
int iabsexp = Math.Abs(iexp);
if (ml < 9007199254740992L && iabsexp == 0) {
return EFloat.FromInt64(negative ?
-mantissaLong : mantissaLong).RoundToPrecision(ctx);
} else if (ml < 9007199254740992L && iabsexp <= 22) {
EFloat efn =
EFloat.FromEInteger(NumberUtility.FindPowerOfTen(iabsexp));
if (negative) {
ml = -ml;
}
EFloat efml = EFloat.FromInt64(ml);
if (iexp < 0) {
return efml.Divide(efn, ctx);
} else {
return efml.Multiply(efn, ctx);
}
}
}
long adjexpUpperBound = finalexp + (decimalPrec - 1);
long adjexpLowerBound = finalexp;
if (adjexpUpperBound < -326) {
return EFloat.SignalUnderflow(ctx, negative, zeroMantissa);
} else if (adjexpLowerBound > 309) {
return EFloat.SignalOverflow(ctx, negative, zeroMantissa);
}
if (negative) {
mantissaLong = -mantissaLong;
}
long absfinalexp = Math.Abs(finalexp);
ef1 = EFloat.Create(mantissaLong, (int)0);
ef2 = EFloat.FromEInteger(NumberUtility.FindPowerOfTen(absfinalexp));
if (finalexp < 0) {
EFloat efret = ef1.Divide(ef2, ctx);
/* Console.WriteLine("div " + ef1 + "/" + ef2 + " -> " + (efret));
*/ return efret;
} else {
return ef1.Multiply(ef2, ctx);
}
}
EInteger mant = null;
EInteger exp = (!haveExponent) ? EInteger.Zero :
EInteger.FromSubstring(chars, expDigitStart, endStr);
if (expoffset < 0) {
exp = exp.Negate();
}
exp = exp.Add(newScaleInt);
if (nonzeroBeyondMax) {
exp = exp.Subtract(1);
++decimalPrec;
}
EInteger adjExpUpperBound = exp.Add(decimalPrec).Subtract(1);
EInteger adjExpLowerBound = exp;
// DebugUtility.Log("exp=" + adjExpLowerBound + "~" + (adjExpUpperBound));
if (adjExpUpperBound.CompareTo(-326) < 0) {
return EFloat.SignalUnderflow(ctx, negative, zeroMantissa);
} else if (adjExpLowerBound.CompareTo(309) > 0) {
return EFloat.SignalOverflow(ctx, negative, zeroMantissa);
}
if (zeroMantissa) {
EFloat ef = EFloat.Create(
EInteger.Zero,
exp);
if (negative) {
ef = ef.Negate();
}
return ef.RoundToPrecision(ctx);
} else if (decimalDigitStart != decimalDigitEnd) {
if (digitEnd - digitStart == 1 && chars[digitStart] == '0') {
mant = EInteger.FromSubstring(
chars,
decimalDigitStart,
decimalDigitEnd);
} else {
byte[] ctmpstr = Extras.CharsConcat(
chars,
digitStart,
digitEnd - digitStart,
chars,
decimalDigitStart,
decimalDigitEnd - decimalDigitStart);
mant = EInteger.FromString(ctmpstr);
}
} else {
mant = EInteger.FromSubstring(chars, digitStart, digitEnd);
}
if (nonzeroBeyondMax) {
mant = mant.Multiply(10).Add(1);
}
if (negative) {
mant = mant.Negate();
}
return EDecimal.Create(mant, exp).ToEFloat(ctx);
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.PlatformAbstractions;
namespace Microsoft.DotNet.Tools.Common
{
public static class PathUtility
{
public static bool IsPlaceholderFile(string path)
{
return string.Equals(Path.GetFileName(path), "_._", StringComparison.Ordinal);
}
public static bool IsChildOfDirectory(string dir, string candidate)
{
if (dir == null)
{
throw new ArgumentNullException(nameof(dir));
}
if (candidate == null)
{
throw new ArgumentNullException(nameof(candidate));
}
dir = Path.GetFullPath(dir);
dir = EnsureTrailingSlash(dir);
candidate = Path.GetFullPath(candidate);
return candidate.StartsWith(dir, StringComparison.OrdinalIgnoreCase);
}
public static string EnsureTrailingSlash(string path)
{
return EnsureTrailingCharacter(path, Path.DirectorySeparatorChar);
}
public static string EnsureTrailingForwardSlash(string path)
{
return EnsureTrailingCharacter(path, '/');
}
private static string EnsureTrailingCharacter(string path, char trailingCharacter)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
// if the path is empty, we want to return the original string instead of a single trailing character.
if (path.Length == 0 || path[path.Length - 1] == trailingCharacter)
{
return path;
}
return path + trailingCharacter;
}
public static string EnsureNoTrailingDirectorySeparator(string path)
{
if (!string.IsNullOrEmpty(path))
{
char lastChar = path[path.Length - 1];
if (lastChar == Path.DirectorySeparatorChar)
{
path = path.Substring(0, path.Length - 1);
}
}
return path;
}
public static void EnsureParentDirectoryExists(string filePath)
{
string directory = Path.GetDirectoryName(filePath);
EnsureDirectoryExists(directory);
}
public static void EnsureDirectoryExists(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
public static bool TryDeleteDirectory(string directoryPath)
{
try
{
Directory.Delete(directoryPath, true);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Returns childItem relative to directory, with Path.DirectorySeparatorChar as separator
/// </summary>
public static string GetRelativePath(DirectoryInfo directory, FileSystemInfo childItem)
{
var path1 = EnsureTrailingSlash(directory.FullName);
var path2 = childItem.FullName;
return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, true);
}
/// <summary>
/// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator
/// </summary>
public static string GetRelativePath(string path1, string path2)
{
return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, true);
}
/// <summary>
/// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator but ignoring directory
/// traversals.
/// </summary>
public static string GetRelativePathIgnoringDirectoryTraversals(string path1, string path2)
{
return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, false);
}
/// <summary>
/// Returns path2 relative to path1, with given path separator
/// </summary>
public static string GetRelativePath(string path1, string path2, char separator, bool includeDirectoryTraversals)
{
if (string.IsNullOrEmpty(path1))
{
throw new ArgumentException("Path must have a value", nameof(path1));
}
if (string.IsNullOrEmpty(path2))
{
throw new ArgumentException("Path must have a value", nameof(path2));
}
StringComparison compare;
if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows)
{
compare = StringComparison.OrdinalIgnoreCase;
// check if paths are on the same volume
if (!string.Equals(Path.GetPathRoot(path1), Path.GetPathRoot(path2)))
{
// on different volumes, "relative" path is just path2
return path2;
}
}
else
{
compare = StringComparison.Ordinal;
}
var index = 0;
var path1Segments = path1.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var path2Segments = path2.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// if path1 does not end with / it is assumed the end is not a directory
// we will assume that is isn't a directory by ignoring the last split
var len1 = path1Segments.Length - 1;
var len2 = path2Segments.Length;
// find largest common absolute path between both paths
var min = Math.Min(len1, len2);
while (min > index)
{
if (!string.Equals(path1Segments[index], path2Segments[index], compare))
{
break;
}
// Handle scenarios where folder and file have same name (only if os supports same name for file and directory)
// e.g. /file/name /file/name/app
else if ((len1 == index && len2 > index + 1) || (len1 > index && len2 == index + 1))
{
break;
}
++index;
}
var path = "";
// check if path2 ends with a non-directory separator and if path1 has the same non-directory at the end
if (len1 + 1 == len2 && !string.IsNullOrEmpty(path1Segments[index]) &&
string.Equals(path1Segments[index], path2Segments[index], compare))
{
return path;
}
if (includeDirectoryTraversals)
{
for (var i = index; len1 > i; ++i)
{
path += ".." + separator;
}
}
for (var i = index; len2 - 1 > i; ++i)
{
path += path2Segments[i] + separator;
}
// if path2 doesn't end with an empty string it means it ended with a non-directory name, so we add it back
if (!string.IsNullOrEmpty(path2Segments[len2 - 1]))
{
path += path2Segments[len2 - 1];
}
return path;
}
public static string GetAbsolutePath(string basePath, string relativePath)
{
if (basePath == null)
{
throw new ArgumentNullException(nameof(basePath));
}
if (relativePath == null)
{
throw new ArgumentNullException(nameof(relativePath));
}
Uri resultUri = new Uri(new Uri(basePath), new Uri(relativePath, UriKind.Relative));
return resultUri.LocalPath;
}
public static string GetDirectoryName(string path)
{
path = path.TrimEnd(Path.DirectorySeparatorChar);
return path.Substring(Path.GetDirectoryName(path).Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
public static string GetPathWithForwardSlashes(string path)
{
return path.Replace('\\', '/');
}
public static string GetPathWithBackSlashes(string path)
{
return path.Replace('/', '\\');
}
public static string GetPathWithDirectorySeparator(string path)
{
if (Path.DirectorySeparatorChar == '/')
{
return GetPathWithForwardSlashes(path);
}
else
{
return GetPathWithBackSlashes(path);
}
}
public static bool HasExtension(string filePath, string extension)
{
var comparison = StringComparison.Ordinal;
if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows)
{
comparison = StringComparison.OrdinalIgnoreCase;
}
return Path.GetExtension(filePath).Equals(extension, comparison);
}
/// <summary>
/// Gets the fully-qualified path without failing if the
/// path is empty.
/// </summary>
public static string GetFullPath(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return path;
}
return Path.GetFullPath(path);
}
public static void EnsureAllPathsExist(List<string> paths, string pathDoesNotExistLocalizedFormatString)
{
var notExisting = new List<string>();
foreach (var p in paths)
{
if (!File.Exists(p))
{
notExisting.Add(p);
}
}
if (notExisting.Count > 0)
{
throw new GracefulException(
string.Join(
Environment.NewLine,
notExisting.Select((p) => string.Format(pathDoesNotExistLocalizedFormatString, p))));
}
}
}
}
| |
using Antlr4.Runtime;
using Plang.Compiler.TypeChecker.AST.Declarations;
using Plang.Compiler.TypeChecker.AST.States;
using Plang.Compiler.TypeChecker.Types;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Plang.Compiler.TypeChecker
{
public static class MachineChecker
{
public static void Validate(ITranslationErrorHandler handler, Machine machine)
{
State startState = FindStartState(machine, handler);
PLanguageType startStatePayloadType = GetStatePayload(startState);
Debug.Assert(startStatePayloadType.IsSameTypeAs(machine.PayloadType));
ValidateHandlers(handler, machine);
ValidateTransitions(handler, machine);
}
private static void ValidateHandlers(ITranslationErrorHandler handler, Machine machine)
{
foreach (var state in machine.AllStates())
{
if (state.Entry?.Signature.Parameters.Count > 1)
{
throw handler.MoreThanOneParameterForHandlers(state.SourceLocation, state.Entry.Signature.Parameters.Count);
}
if (state.Exit?.Signature.Parameters.Count > 0)
{
throw handler.ExitFunctionCannotTakeParameters(state.SourceLocation, state.Exit.Signature.Parameters.Count);
}
foreach (KeyValuePair<PEvent, AST.IStateAction> pair in state.AllEventHandlers)
{
PEvent handledEvent = pair.Key;
switch (pair.Value)
{
case EventDoAction eventDoAction:
if (eventDoAction.Target != null && eventDoAction.Target.Signature.ParameterTypes.Count() > 1)
{
throw handler.MoreThanOneParameterForHandlers(eventDoAction.SourceLocation,
eventDoAction.Target.Signature.ParameterTypes.Count());
}
break;
case EventGotoState eventGotoState:
if (eventGotoState.TransitionFunction != null && eventGotoState.TransitionFunction.Signature.ParameterTypes.Count() > 1)
{
throw handler.MoreThanOneParameterForHandlers(eventGotoState.SourceLocation,
eventGotoState.TransitionFunction.Signature.ParameterTypes.Count());
}
break;
case EventDefer _:
case EventIgnore _:
{
break;
}
}
}
}
}
public static void ValidateNoStaticHandlers(ITranslationErrorHandler handler, Machine machine)
{
foreach (State state in machine.AllStates())
{
bool illegalUsage = state.Entry != null && IsStaticOrForeign(state.Entry);
if (illegalUsage)
{
throw handler.StaticFunctionNotAllowedAsHandler(state.SourceLocation,
state.Entry.Name);
}
illegalUsage = state.Exit != null && IsStaticOrForeign(state.Exit);
if (illegalUsage)
{
throw handler.StaticFunctionNotAllowedAsHandler(state.SourceLocation,
state.Exit.Name);
}
foreach (KeyValuePair<PEvent, AST.IStateAction> pair in state.AllEventHandlers)
{
switch (pair.Value)
{
case EventDoAction eventDoAction:
if (eventDoAction.Target != null && IsStaticOrForeign(eventDoAction.Target))
{
throw handler.StaticFunctionNotAllowedAsHandler(eventDoAction.SourceLocation,
eventDoAction.Target.Name);
}
break;
case EventGotoState eventGotoState:
if (eventGotoState.TransitionFunction != null &&
IsStaticOrForeign(eventGotoState.TransitionFunction))
{
throw handler.StaticFunctionNotAllowedAsHandler(eventGotoState.SourceLocation,
eventGotoState.TransitionFunction.Name);
}
break;
case EventDefer _:
case EventIgnore _:
break;
default:
throw handler.InternalError(pair.Value.SourceLocation,
new System.Exception("Unknown transition type parsed, report to the P team"));
}
}
}
}
private static bool IsStaticOrForeign(Function function)
{
return function.Owner == null || function.IsForeign;
}
private static void ValidateTransitions(ITranslationErrorHandler handler, Machine machine)
{
foreach (State state in machine.AllStates())
{
foreach (KeyValuePair<PEvent, AST.IStateAction> pair in state.AllEventHandlers)
{
PEvent handledEvent = pair.Key;
switch (pair.Value)
{
case EventDoAction eventDoAction:
if (eventDoAction.Target != null)
{
ValidateEventPayloadToTransitionTarget(handler: handler, sourceLocation: eventDoAction.SourceLocation,
eventPayloadType: handledEvent.PayloadType, targetFunction: eventDoAction.Target);
}
break;
case EventGotoState eventGotoState:
if (eventGotoState.Target.Entry != null)
{
ValidateEventPayloadToTransitionTarget(handler: handler, sourceLocation: eventGotoState.SourceLocation,
eventPayloadType: handledEvent.PayloadType, targetFunction: eventGotoState.Target.Entry);
}
if (eventGotoState.TransitionFunction != null)
{
ValidateEventPayloadToTransitionTarget(handler: handler, sourceLocation: eventGotoState.SourceLocation,
eventPayloadType: handledEvent.PayloadType, targetFunction: eventGotoState.TransitionFunction);
}
break;
case EventDefer _:
case EventIgnore _:
{
break;
}
}
}
}
}
private static void ValidateEventPayloadToTransitionTarget(ITranslationErrorHandler handler,
ParserRuleContext sourceLocation,
PLanguageType eventPayloadType,
Function targetFunction)
{
IReadOnlyList<PLanguageType> entrySignature = targetFunction.Signature.ParameterTypes.ToList();
if (entrySignature.Count == 0)
{
return;
}
if (entrySignature.Count > 1)
{
throw handler.InternalError(sourceLocation, new System.Exception("Target function cannot have multiple parameters (report this to the P developers)"));
}
if (entrySignature.Count == 1 && entrySignature[0].IsAssignableFrom(eventPayloadType))
{
return;
}
if (entrySignature.Count == 1 && eventPayloadType.Canonicalize() is TupleType tuple &&
tuple.Types.Count == 1 && entrySignature[0].IsAssignableFrom(tuple.Types[0]))
{
return;
}
if (entrySignature.Count == 1)
{
throw handler.TypeMismatch(sourceLocation, eventPayloadType, entrySignature[0]);
}
PLanguageType entrySignatureType = new TupleType(entrySignature.ToArray());
if (!entrySignatureType.IsAssignableFrom(eventPayloadType))
{
throw handler.TypeMismatch(sourceLocation, eventPayloadType, entrySignatureType);
}
}
private static PLanguageType GetStatePayload(State startState)
{
if (!(startState.Entry?.Signature.Parameters.Count > 0))
{
return PrimitiveType.Null;
}
Debug.Assert(startState.Entry.Signature.Parameters.Count == 1,
"Allowed start state entry with multiple parameters");
return startState.Entry.Signature.Parameters[0].Type;
}
private static State FindStartState(Machine machine, ITranslationErrorHandler handler)
{
bool foundStartState = false;
foreach (State state in machine.AllStates())
{
if (state == machine.StartState || state.IsStart)
{
if (!foundStartState)
{
foundStartState = true;
}
else
{
throw handler.TwoStartStates(machine, state);
}
}
}
Debug.Assert(!(foundStartState && machine.StartState == null), "machine has unregistered start state");
if (!foundStartState || machine.StartState == null)
{
throw handler.MissingStartState(machine);
}
return machine.StartState;
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. 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.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapSearchConstraints.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System.Collections;
namespace Novell.Directory.Ldap
{
/// <summary>
/// Defines the options controlling search operations.
/// An LdapSearchConstraints object is always associated with an
/// LdapConnection object; its values can be changed with the
/// LdapConnection.setConstraints method, or overridden by passing
/// an LdapSearchConstraints object to the search operation.
/// </summary>
/// <seealso cref="LdapConstraints">
/// </seealso>
/// <seealso cref="LdapConnection.Constraints">
/// </seealso>
public class LdapSearchConstraints : LdapConstraints
{
private void InitBlock()
{
dereference = DEREF_NEVER;
}
/// <summary>
/// Returns the number of results to block on during receipt of search
/// results.
/// This should be 0 if intermediate reults are not needed,
/// and 1 if results are to be processed as they come in. A value of
/// indicates block until all results are received. Default:
/// </summary>
/// <returns>
/// The the number of results to block on.
/// </returns>
/// <seealso cref="BatchSize">
/// </seealso>
/// <summary>
/// Specifies the number of results to return in a batch.
/// Specifying 0 means to block until all results are received.
/// Specifying 1 means to return results one result at a time. Default: 1
/// This should be 0 if intermediate results are not needed,
/// and 1 if results are to be processed as they come in. The
/// default is 1.
/// </summary>
/// <param name="batchSize">
/// The number of results to block on.
/// </param>
/// <seealso cref="BatchSize">
/// </seealso>
public virtual int BatchSize
{
get { return batchSize; }
set { batchSize = value; }
}
/// <summary>
/// Specifies when aliases should be dereferenced.
/// Returns one of the following:
/// <ul>
/// <li>DEREF_NEVER</li>
/// <li>DEREF_FINDING</li>
/// <li>DEREF_SEARCHING</li>
/// <li>DEREF_ALWAYS</li>
/// </ul>
/// </summary>
/// <returns>
/// The setting for dereferencing aliases.
/// </returns>
/// <seealso cref="Dereference">
/// </seealso>
/// <summary>
/// Sets a preference indicating whether or not aliases should be
/// dereferenced, and if so, when.
/// </summary>
/// <param name="dereference">
/// Specifies how aliases are dereference and can be set
/// to one of the following:
/// <ul>
/// <li>DEREF_NEVER - do not dereference aliases</li>
/// <li>
/// DEREF_FINDING - dereference aliases when finding
/// the base object to start the search
/// </li>
/// <li>
/// DEREF_SEARCHING - dereference aliases when
/// searching but not when finding the base
/// object to start the search
/// </li>
/// <li>
/// DEREF_ALWAYS - dereference aliases when finding
/// the base object and when searching
/// </li>
/// </ul>
/// </param>
/// <seealso cref="Dereference">
/// </seealso>
public virtual int Dereference
{
get { return dereference; }
set { dereference = value; }
}
/// <summary>
/// Returns the maximum number of search results to be returned for
/// a search operation. A value of 0 means no limit. Default: 1000
/// The search operation will be terminated with an
/// LdapException.SIZE_LIMIT_EXCEEDED if the number of results
/// exceed the maximum.
/// </summary>
/// <returns>
/// The value for the maximum number of results to return.
/// </returns>
/// <seealso cref="MaxResults">
/// </seealso>
/// <seealso cref="LdapException.SIZE_LIMIT_EXCEEDED">
/// </seealso>
/// <summary>
/// Sets the maximum number of search results to be returned from a
/// search operation. The value 0 means no limit. The default is 1000.
/// The search operation will be terminated with an
/// LdapException.SIZE_LIMIT_EXCEEDED if the number of results
/// exceed the maximum.
/// </summary>
/// <param name="maxResults">
/// Maximum number of search results to return.
/// </param>
/// <seealso cref="MaxResults">
/// </seealso>
/// <seealso cref="LdapException.SIZE_LIMIT_EXCEEDED">
/// </seealso>
public virtual int MaxResults
{
get { return maxResults; }
set { maxResults = value; }
}
/// <summary>
/// Returns the maximum number of seconds that the server waits when
/// returning search results.
/// The search operation will be terminated with an
/// LdapException.TIME_LIMIT_EXCEEDED if the operation exceeds the time
/// limit.
/// </summary>
/// <returns>
/// The maximum number of seconds the server waits for search'
/// results.
/// </returns>
/// <seealso cref="ServerTimeLimit">
/// </seealso>
/// <seealso cref="LdapException.TIME_LIMIT_EXCEEDED">
/// </seealso>
/// <summary>
/// Sets the maximum number of seconds that the server is to wait when
/// returning search results.
/// The search operation will be terminated with an
/// LdapException.TIME_LIMIT_EXCEEDED if the operation exceeds the time
/// limit.
/// The parameter is only recognized on search operations.
/// </summary>
/// <param name="seconds">
/// The number of seconds to wait for search results.
/// </param>
/// <seealso cref="ServerTimeLimit">
/// </seealso>
/// <seealso cref="LdapException.TIME_LIMIT_EXCEEDED">
/// </seealso>
public virtual int ServerTimeLimit
{
get { return serverTimeLimit; }
set { serverTimeLimit = value; }
}
private int dereference;
private int serverTimeLimit;
private int maxResults = 1000;
private int batchSize = 1;
private static object nameLock; // protect agentNum
private static int lSConsNum = 0; // Debug, LdapConnection number
private string name; // String name for debug
/// <summary>
/// Indicates that aliases are never dereferenced.
/// DEREF_NEVER = 0
/// </summary>
/// <seealso cref="Dereference">
/// </seealso>
/// <seealso cref="Dereference">
/// </seealso>
public const int DEREF_NEVER = 0;
/// <summary>
/// Indicates that aliases are are derefrenced when
/// searching the entries beneath the starting point of the search,
/// but not when finding the starting entry.
/// DEREF_SEARCHING = 1
/// </summary>
/// <seealso cref="Dereference">
/// </seealso>
/// <seealso cref="Dereference">
/// </seealso>
public const int DEREF_SEARCHING = 1;
/// <summary>
/// Indicates that aliases are dereferenced when
/// finding the starting point for the search,
/// but not when searching under that starting entry.
/// DEREF_FINDING = 2
/// </summary>
/// <seealso cref="Dereference">
/// </seealso>
/// <seealso cref="Dereference">
/// </seealso>
public const int DEREF_FINDING = 2;
/// <summary>
/// Indicates that aliases are always dereferenced, both when
/// finding the starting point for the search, and also when
/// searching the entries beneath the starting entry.
/// DEREF_ALWAYS = 3
/// </summary>
/// <seealso cref="Dereference">
/// </seealso>
/// <seealso cref="Dereference">
/// </seealso>
public const int DEREF_ALWAYS = 3;
/// <summary>
/// Constructs an LdapSearchConstraints object with a default set
/// of search constraints.
/// </summary>
public LdapSearchConstraints()
{
InitBlock();
// Get a unique connection name for debug
}
/// <summary>
/// Constructs an LdapSearchConstraints object initialized with values
/// from an existing constraints object (LdapConstraints
/// or LdapSearchConstraints).
/// </summary>
public LdapSearchConstraints(LdapConstraints cons)
: base(cons.TimeLimit, cons.ReferralFollowing, cons.getReferralHandler(), cons.HopLimit)
{
InitBlock();
var lsc = cons.getControls();
if (lsc != null)
{
var generated_var = new LdapControl[lsc.Length];
lsc.CopyTo(generated_var, 0);
setControls(generated_var);
}
var lp = cons.Properties;
if (lp != null)
{
Properties = (Hashtable) lp.Clone();
}
if (cons is LdapSearchConstraints)
{
var scons = (LdapSearchConstraints) cons;
serverTimeLimit = scons.ServerTimeLimit;
dereference = scons.Dereference;
maxResults = scons.MaxResults;
batchSize = scons.BatchSize;
}
// Get a unique connection name for debug
}
/// <summary>
/// Constructs a new LdapSearchConstraints object and allows the
/// specification operational constraints in that object.
/// </summary>
/// <param name="msLimit">
/// The maximum time in milliseconds to wait for results.
/// The default is 0, which means that there is no
/// maximum time limit. This limit is enforced for an
/// operation by the API, not by the server.
/// The operation will be abandoned and terminated by the
/// API with an LdapException.Ldap_TIMEOUT if the
/// operation exceeds the time limit.
/// </param>
/// <param name="serverTimeLimit">
/// The maximum time in seconds that the server
/// should spend returning search results. This is a
/// server-enforced limit. The default of 0 means
/// no time limit.
/// The operation will be terminated by the server with an
/// LdapException.TIME_LIMIT_EXCEEDED if the search
/// operation exceeds the time limit.
/// </param>
/// <param name="dereference">
/// Specifies when aliases should be dereferenced.
/// Must be either DEREF_NEVER, DEREF_FINDING,
/// DEREF_SEARCHING, or DEREF_ALWAYS from this class.
/// Default: DEREF_NEVER
/// </param>
/// <param name="maxResults">
/// The maximum number of search results to return
/// for a search request.
/// The search operation will be terminated by the server
/// with an LdapException.SIZE_LIMIT_EXCEEDED if the
/// number of results exceed the maximum.
/// Default: 1000
/// </param>
/// <param name="doReferrals">
/// Determines whether to automatically follow
/// referrals or not. Specify true to follow
/// referrals automatically, and false to throw
/// an LdapException.REFERRAL if the server responds
/// with a referral.
/// It is ignored for asynchronous operations.
/// Default: false
/// </param>
/// <param name="batchSize">
/// The number of results to return in a batch. Specifying
/// 0 means to block until all results are received.
/// Specifying 1 means to return results one result at a
/// time. Default: 1
/// </param>
/// <param name="handler">
/// The custom authentication handler called when
/// LdapConnection needs to authenticate, typically on
/// following a referral. A null may be specified to
/// indicate default authentication processing, i.e.
/// referrals are followed with anonymous authentication.
/// ThE object may be an implemention of either the
/// the LdapBindHandler or LdapAuthHandler interface.
/// It is ignored for asynchronous operations.
/// </param>
/// <param name="hop_limit">
/// The maximum number of referrals to follow in a
/// sequence during automatic referral following.
/// The default value is 10. A value of 0 means no limit.
/// It is ignored for asynchronous operations.
/// The operation will be abandoned and terminated by the
/// API with an LdapException.REFERRAL_LIMIT_EXCEEDED if the
/// number of referrals in a sequence exceeds the limit.
/// </param>
/// <seealso cref="LdapException.Ldap_TIMEOUT">
/// </seealso>
/// <seealso cref="LdapException.REFERRAL">
/// </seealso>
/// <seealso cref="LdapException.SIZE_LIMIT_EXCEEDED">
/// </seealso>
/// <seealso cref="LdapException.TIME_LIMIT_EXCEEDED">
/// </seealso>
public LdapSearchConstraints(int msLimit, int serverTimeLimit, int dereference, int maxResults, bool doReferrals,
int batchSize, LdapReferralHandler handler, int hop_limit) : base(msLimit, doReferrals, handler, hop_limit)
{
InitBlock();
this.serverTimeLimit = serverTimeLimit;
this.dereference = dereference;
this.maxResults = maxResults;
this.batchSize = batchSize;
// Get a unique connection name for debug
}
static LdapSearchConstraints()
{
nameLock = new object();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using StructureMap.Building;
using StructureMap.Diagnostics;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.TypeRules;
namespace StructureMap
{
public class BuildSession : IBuildSession, IContext
{
public static readonly string DEFAULT = "Default";
private readonly IPipelineGraph _pipelineGraph;
private readonly ISessionCache _sessionCache;
private readonly Stack<Instance> _instances = new Stack<Instance>();
public BuildSession(IPipelineGraph pipelineGraph, string requestedName = null, ExplicitArguments args = null)
{
_pipelineGraph = pipelineGraph;
_sessionCache = new SessionCache(this, args);
RequestedName = requestedName ?? DEFAULT;
}
protected IPipelineGraph pipelineGraph
{
get { return _pipelineGraph; }
}
public string RequestedName { get; set; }
public void BuildUp(object target)
{
if (target == null) throw new ArgumentNullException("target");
var pluggedType = target.GetType();
var plan = _pipelineGraph.Policies.ToBuildUpPlan(pluggedType, () => {
return _pipelineGraph.Instances.GetDefault(pluggedType) as IConfiguredInstance
?? new ConfiguredInstance(pluggedType);
});
plan.BuildUp(this, this, target);
}
public T GetInstance<T>()
{
return (T) GetInstance(typeof (T));
}
public object GetInstance(Type pluginType)
{
return _sessionCache.GetDefault(pluginType, _pipelineGraph);
}
public T GetInstance<T>(string name)
{
return (T) CreateInstance(typeof (T), name);
}
public object GetInstance(Type pluginType, string name)
{
return CreateInstance(pluginType, name);
}
public T TryGetInstance<T>() where T : class
{
return (T) TryGetInstance(typeof (T));
}
public T TryGetInstance<T>(string name) where T : class
{
return (T) TryGetInstance(typeof (T), name);
}
public object TryGetInstance(Type pluginType)
{
return _sessionCache.TryGetDefault(pluginType, _pipelineGraph);
}
public object TryGetInstance(Type pluginType, string name)
{
return _pipelineGraph.Instances.HasInstance(pluginType, name)
? ((IContext) this).GetInstance(pluginType, name)
: null;
}
public IEnumerable<T> All<T>() where T : class
{
return _sessionCache.All<T>();
}
public object ResolveFromLifecycle(Type pluginType, Instance instance)
{
var cache = _pipelineGraph.DetermineLifecycle(pluginType, instance).FindCache(_pipelineGraph);
return cache.Get(pluginType, instance, this);
}
public object BuildNewInSession(Type pluginType, Instance instance)
{
if (pluginType == null) throw new ArgumentNullException("pluginType");
if (instance == null) throw new ArgumentNullException("instance");
if (RootType == null) RootType = instance.ReturnedType;
var plan = instance.ResolveBuildPlan(pluginType, _pipelineGraph.Policies);
return plan.Build(this, this);
}
public object BuildUnique(Type pluginType, Instance instance)
{
var @object = BuildNewInSession(pluginType, instance);
if (@object is IDisposable && _pipelineGraph.Role == ContainerRole.Nested)
{
_pipelineGraph.TrackDisposable((IDisposable) @object);
}
return @object;
}
public object BuildNewInOriginalContext(Type pluginType, Instance instance)
{
var session = new BuildSession(pipelineGraph.Root(), requestedName: instance.Name);
return session.BuildNewInSession(pluginType, instance);
}
public IEnumerable<T> GetAllInstances<T>()
{
return
_pipelineGraph.Instances.GetAllInstances(typeof (T))
.Select(x => (T) FindObject(typeof (T), x))
.ToArray();
}
public IEnumerable<object> GetAllInstances(Type pluginType)
{
var allInstances = _pipelineGraph.Instances.GetAllInstances(pluginType);
return allInstances.Select(x => FindObject(pluginType, x)).ToArray();
}
public static BuildSession ForPluginGraph(PluginGraph graph, ExplicitArguments args = null)
{
var pipeline = PipelineGraph.BuildRoot(graph);
return new BuildSession(pipeline, args: args);
}
public static BuildSession Empty(ExplicitArguments args = null)
{
return ForPluginGraph(PluginGraph.CreateRoot(), args);
}
public virtual object CreateInstance(Type pluginType, string name)
{
var instance = _pipelineGraph.Instances.FindInstance(pluginType, name);
if (instance == null)
{
var ex =
new StructureMapConfigurationException("Could not find an Instance named '{0}' for PluginType {1}",
name, pluginType.GetFullName());
ex.Context = new WhatDoIHaveWriter(_pipelineGraph).GetText(new ModelQuery {PluginType = pluginType},
"The current configuration for type {0} is:".ToFormat(pluginType.GetFullName()));
throw ex;
}
RootType = instance.ReturnedType;
return FindObject(pluginType, instance);
}
public void Push(Instance instance)
{
if (_instances.Contains(instance))
{
throw new StructureMapBuildException("Bi-directional dependency relationship detected!" +
Environment.NewLine + "Check the StructureMap stacktrace below:");
}
_instances.Push(instance);
}
public void Pop()
{
if (_instances.Any())
{
_instances.Pop();
}
}
public Type ParentType
{
get
{
if (_instances.Count > 1)
{
return _instances.ToArray().Skip(1).First().ReturnedType;
}
return null;
}
}
public Type RootType { get; internal set; }
// This is where all Creation happens
public virtual object FindObject(Type pluginType, Instance instance)
{
RootType = instance.ReturnedType;
var lifecycle = _pipelineGraph.DetermineLifecycle(pluginType, instance);
return _sessionCache.GetObject(pluginType, instance, lifecycle);
}
public Policies Policies
{
get { return _pipelineGraph.Policies; }
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
////////////////////////////////////////////////////////////////
// Module: use CXMLTypeCoercionTestModule
//
////////////////////////////////////////////////////////////////
[TestModule(Name = "XmlFactoryReader Test", Desc = "XmlFactoryReader Test")]
public partial class FactoryReaderTest : CGenericTestModule
{
public override int Init(object objParam)
{
int ret = base.Init(objParam);
// Create global usage test files
string strFile = String.Empty;
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.XSLT_COPY);
// Create reader factory
ReaderFactory = new XmlFactoryReaderFactory();
return ret;
}
public override int Terminate(object objParam)
{
return base.Terminate(objParam);
}
}
////////////////////////////////////////////////////////////////
// FactoryReader factory
//
////////////////////////////////////////////////////////////////
internal class XmlFactoryReaderFactory : ReaderFactory
{
public override XmlReader Create(MyDict<string, object> options)
{
string tcDesc = (string)options[ReaderFactory.HT_CURDESC];
string tcVar = (string)options[ReaderFactory.HT_CURVAR];
CError.Compare(tcDesc == "factoryreader", "Invalid testcase");
XmlReaderSettings rs = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
Stream stream = (Stream)options[ReaderFactory.HT_STREAM];
string filename = (string)options[ReaderFactory.HT_FILENAME];
object readerType = options[ReaderFactory.HT_READERTYPE];
object vt = options[ReaderFactory.HT_VALIDATIONTYPE];
string fragment = (string)options[ReaderFactory.HT_FRAGMENT];
StringReader sr = (StringReader)options[ReaderFactory.HT_STRINGREADER];
if (rs == null)
rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Ignore;
if (sr != null)
{
CError.WriteLine("StringReader");
XmlReader reader = ReaderHelper.Create(sr, rs, string.Empty);
return reader;
}
if (stream != null)
{
CError.WriteLine("Stream");
XmlReader reader = ReaderHelper.Create(stream, rs, filename);
return reader;
}
if (fragment != null)
{
CError.WriteLine("Fragment");
rs.ConformanceLevel = ConformanceLevel.Fragment;
StringReader tr = new StringReader(fragment);
XmlReader reader = ReaderHelper.Create(tr, rs, (string)null);
return reader;
}
if (filename != null)
{
CError.WriteLine("Filename");
XmlReader reader = ReaderHelper.Create(filename, rs);
return reader;
}
throw new
CTestFailedException("Factory Reader not created");
}
}
[TestCase(Name = "ErrorCondition", Desc = "FactoryReader")]
internal class TCErrorConditionReader : TCErrorCondition
{
}
[TestCase(Name = "XMLException", Desc = "FactoryReader")]
public class TCXMLExceptionReader : TCXMLException
{
}
[TestCase(Name = "LinePos", Desc = "FactoryReader")]
public class TCLinePosReader : TCLinePos
{
}
[TestCase(Name = "Depth", Desc = "FactoryReader")]
internal class TCDepthReader : TCDepth
{
}
[TestCase(Name = "Namespace", Desc = "FactoryReader")]
internal class TCNamespaceReader : TCNamespace
{
}
[TestCase(Name = "LookupNamespace", Desc = "FactoryReader")]
internal class TCLookupNamespaceReader : TCLookupNamespace
{
}
[TestCase(Name = "HasValue", Desc = "FactoryReader")]
internal class TCHasValueReader : TCHasValue
{
}
[TestCase(Name = "IsEmptyElement", Desc = "FactoryReader")]
internal class TCIsEmptyElementReader : TCIsEmptyElement
{
}
[TestCase(Name = "XmlSpace", Desc = "FactoryReader")]
internal class TCXmlSpaceReader : TCXmlSpace
{
}
[TestCase(Name = "XmlLang", Desc = "FactoryReader")]
internal class TCXmlLangReader : TCXmlLang
{
}
[TestCase(Name = "Skip", Desc = "FactoryReader")]
internal class TCSkipReader : TCSkip
{
}
[TestCase(Name = "BaseURI", Desc = "FactoryReader")]
internal class TCBaseURIReader : TCBaseURI
{
}
[TestCase(Name = "InvalidXML", Desc = "FactoryReader")]
internal class TCInvalidXMLReader : TCInvalidXML
{
}
[TestCase(Name = "ReadOuterXml", Desc = "FactoryReader")]
internal class TCReadOuterXmlReader : TCReadOuterXml
{
}
[TestCase(Name = "AttributeAccess", Desc = "FactoryReader")]
internal class TCAttributeAccessReader : TCAttributeAccess
{
}
[TestCase(Name = "This(Name) and This(Name, Namespace)", Desc = "FactoryReader")]
internal class TCThisNameReader : TCThisName
{
}
[TestCase(Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "FactoryReader")]
internal class TCMoveToAttributeReader : TCMoveToAttribute
{
}
[TestCase(Name = "GetAttribute (Ordinal)", Desc = "FactoryReader")]
internal class TCGetAttributeOrdinalReader : TCGetAttributeOrdinal
{
}
[TestCase(Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "FactoryReader")]
internal class TCGetAttributeNameReader : TCGetAttributeName
{
}
[TestCase(Name = "This [Ordinal]", Desc = "FactoryReader")]
internal class TCThisOrdinalReader : TCThisOrdinal
{
}
[TestCase(Name = "MoveToAttribute(Ordinal)", Desc = "FactoryReader")]
internal class TCMoveToAttributeOrdinalReader : TCMoveToAttributeOrdinal
{
}
[TestCase(Name = "MoveToFirstAttribute()", Desc = "FactoryReader")]
internal class TCMoveToFirstAttributeReader : TCMoveToFirstAttribute
{
}
[TestCase(Name = "MoveToNextAttribute()", Desc = "FactoryReader")]
internal class TCMoveToNextAttributeReader : TCMoveToNextAttribute
{
}
[TestCase(Name = "Attribute Test when NodeType != Attributes", Desc = "FactoryReader")]
internal class TCAttributeTestReader : TCAttributeTest
{
}
[TestCase(Name = "Attributes test on XmlDeclaration DCR52258", Desc = "FactoryReader")]
internal class TCAttributeXmlDeclarationReader : TCAttributeXmlDeclaration
{
}
[TestCase(Name = "xmlns as local name DCR50345", Desc = "FactoryReader")]
internal class TCXmlnsReader : TCXmlns
{
}
[TestCase(Name = "bounded namespace to xmlns prefix DCR50881", Desc = "FactoryReader")]
internal class TCXmlnsPrefixReader : TCXmlnsPrefix
{
}
[TestCase(Name = "ReadState", Desc = "FactoryReader")]
internal class TCReadStateReader : TCReadState
{
}
[TestCase(Name = "ReadInnerXml", Desc = "FactoryReader")]
internal class TCReadInnerXmlReader : TCReadInnerXml
{
}
[TestCase(Name = "MoveToContent", Desc = "FactoryReader")]
internal class TCMoveToContentReader : TCMoveToContent
{
}
[TestCase(Name = "IsStartElement", Desc = "FactoryReader")]
internal class TCIsStartElementReader : TCIsStartElement
{
}
[TestCase(Name = "ReadStartElement", Desc = "FactoryReader")]
internal class TCReadStartElementReader : TCReadStartElement
{
}
[TestCase(Name = "ReadEndElement", Desc = "FactoryReader")]
internal class TCReadEndElementReader : TCReadEndElement
{
}
[TestCase(Name = "ResolveEntity and ReadAttributeValue", Desc = "FactoryReader")]
internal class TCResolveEntityReader : TCResolveEntity
{
}
[TestCase(Name = "ReadAttributeValue", Desc = "FactoryReader")]
internal class TCReadAttributeValueReader : TCReadAttributeValue
{
}
[TestCase(Name = "Read", Desc = "FactoryReader")]
internal class TCReadReader : TCRead2
{
}
[TestCase(Name = "MoveToElement", Desc = "FactoryReader")]
internal class TCMoveToElementReader : TCMoveToElement
{
}
[TestCase(Name = "Dispose", Desc = "FactoryReader")]
internal class TCDisposeReader : TCDispose
{
}
[TestCase(Name = "Buffer Boundaries", Desc = "FactoryReader")]
internal class TCBufferBoundariesReader : TCBufferBoundaries
{
}
//[TestCase(Name = "BeforeRead", Desc = "BeforeRead")]
//[TestCase(Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse")]
//[TestCase(Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle")]
//[TestCase(Name = "AfterClose", Desc = "AfterClose")]
internal class TCXmlNodeIntegrityTestFile : TCXMLIntegrityBase
{
}
[TestCase(Name = "Read Subtree", Desc = "FactoryReader")]
internal class TCReadSubtreeReader : TCReadSubtree
{
}
[TestCase(Name = "ReadToDescendant", Desc = "FactoryReader")]
internal class TCReadToDescendantReader : TCReadToDescendant
{
}
[TestCase(Name = "ReadToNextSibling", Desc = "FactoryReader")]
internal class TCReadToNextSiblingReader : TCReadToNextSibling
{
}
[TestCase(Name = "ReadValue", Desc = "FactoryReader")]
internal class TCReadValueReader : TCReadValue
{
}
[TestCase(Name = "ReadContentAsBase64", Desc = "FactoryReader")]
internal class TCReadContentAsBase64Reader : TCReadContentAsBase64
{
}
[TestCase(Name = "ReadElementContentAsBase64", Desc = "FactoryReader")]
internal class TCReadElementContentAsBase64Reader : TCReadElementContentAsBase64
{
}
[TestCase(Name = "ReadContentAsBinHex", Desc = "FactoryReader")]
internal class TCReadContentAsBinHexReader : TCReadContentAsBinHex
{
}
[TestCase(Name = "ReadElementContentAsBinHex", Desc = "FactoryReader")]
internal class TCReadElementContentAsBinHexReader : TCReadElementContentAsBinHex
{
}
[TestCase(Name = "ReadToFollowing", Desc = "FactoryReader")]
internal class TCReadToFollowingReader : TCReadToFollowing
{
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.